Having problem to convert Vb method into C# method - c#

I wont to convert this VB method below into c# method. This method should calculate number of days for Rent and then multiply that number with txtRate textbox, so I can get the final number (txtTotal) which can be after stored into data grid view.
VB Method
Sub GetTotal()
Try
Dim day As Integer
day = DateDiff("d", Now.Date.ToString("MM-dd-yyyy"), DateTimePicker1.Value.ToString("MM-dd-yyyy"))
day += 1
lblDay.Text = day
txtTotal.Text = Format(day * CDbl(txtRate.Text), "#,##0.00")
Catch ex As Exception
txtTotal.Text = "0.00"
End Try
End Sub
I did not find any similar method like vb DateDiff is and that is the main problem.

You can just subtract one DateTime from another. It realizes a TimeSpan, which has a TotalDays property:
//if the date time picker date is in the future
(dateTimePicker1.Value - DateTime.Now).TotalDays
TotalDays is a decimal number, like 1.5. One thing to note with a lot of DateDiff functions (SQLServer, VBA, and maybe hence also VB - I can't quite remember) is that they give you the number of times the interval has changed between the dates which is subtly different to a time span
For example asking SQLServer's DateDiff for the years between 2020-12-31 23:59:59 and 2021-01-01 00:00:01 will say "1 year" because the year rocker up from 2020 to 2021, even though only 2 seconds have passed between the two dates
As such if you do specifically need that "imprecise" behavior, you might want to carefully assess whether a TineSpan route (which is very accurate and would give a TotalDays of eg 0.0000235 for the 2 seconds example a live whereas DateDiff would have said 1)

I managed to solve firs part of the problem. My current solution is this :
private void GetTotal()
{
try
{
DateTime d1 = DateTime.Now;
DateTime d2 = dtReturn.Value;
TimeSpan diff = d2.Subtract(d1);
lblDay.Text = diff.Days.ToString("0.00"); //here I get number of Rent days
}
catch (Exception)
{
txtTotal.Text = "0.00";
}
}
Now I need to multiply Value from lblDay with another txt fild (txtRate) so I can get a Total Value wich is stored into txtTotal Field. After I need to store transaction into data grid view

Related

How do I get the between of the dates in my listbox for each line?

I am trying to make an application that can add dates for hotel rooms and get the average time between the dates. I have made 2 calendars, 1 for the starting date and the other one for the ending date. When I show the output in the listbox, I don't know how to get the days between this dates. I need them to calculate the average.
I've tried to get the dates but I'm confused with the datetime things.
lbDates.Items.Add(string.Format("{0}, {1}, {2}, {3}", cmbBoxRoom.SelectedItem, tbBooking.Text, calArrival.SelectedDate, calDeparture.SelectedDate));
How can I get the between of the dates so I can calculate with that?
Please refer the below code
DateTime a = DateTime.Now;
Console.WriteLine("Start Date: " +Convert.ToString(a));
DateTime b = DateTime.Now.AddDays(5).AddHours(5);
//b = b.ToUniversalTime();
Console.WriteLine("End Date: " +Convert.ToString(b));
TimeSpan result = b - a;
//Your code goes here
Console.WriteLine(Convert.ToString(result));
Two variable a & b takes values for start and end date.
Result wil show the output difference between both in Days.Hours:Minutes:Seconds
Check below link
https://rextester.com/PZQ26216
It looks like you simply want to get the time between two dates. In C# this is trivially easy using the DateTime.Subract() method like so:
TimeSpan deltaTime = calDeparture.SelectedDate.Subtract(calArrival.SelectedDate);
or you can use the plain old - operator
Timespan deltaTime = calDeparture.SelectedDate - calArrival.SelectedDate;
This is the same as using the Subtract Method
The deltaTime time variable is a TimeSpan holding the amount of time in between the two dates, you can now (for example) do deltaTime.Days to get the amount of days in between the two dates

Finding if the two DateTime is within a week

I wanted to find if two DateTime are within a week.
One of them is the current system Datetime, which I got it by using:
DateTime CurrentDateTime = new DateTime();
CurrentDateTime = DateTime.Now;
The other DateTime will just be a selected date. Assuming it is stored in a variable called : ExportDate.
So, I can find the difference between them by doing
ExportDate.Subtract(CurrentDateTime)
But I cannot change this value into a int for comparing...
So how should I compare this to DateTime to see if this two dates are greater then 0Days, and less then 7Days.
Subtracting two datetimes gives you a TimeSpan. This class comes with a property called TotalDays.
Gets the value of the current TimeSpan structure expressed in whole and fractional days.
Src: https://msdn.microsoft.com/en-Us/library/system.timespan(v=vs.110).aspx
You can use to count the number of days I guess.
Regards,
Seb
Try to compare the TotalDays of the resulting TimeSpan. Depending on which is later, the result must be between -7 and 7. Use Math.Abs to avoid comparing the value against both bounds:
bool isWithinWeek = Math.Abs(ExportDate - CurrentDate).TotalDays) < 7
If the time of day is irrelevant, compare only the dates:
bool isWithinWeek = Math.Abs(ExportDate.Date - CurrentDate.Date).TotalDays) < 7
You can use
(ExportDate - CurrentDateTime).TotalDays <= 7
You can simply use the DayOfYear property of DateTime to get the day in the year and then check if the difference is less than 7 or not. You can try:
bool isWithinAWeek = Math.Abs(currentDateTime.DayOfYear-exportDate.DayOfYear)>7?false:true;

Exact c# result of sql datediff

I'm trying to get the number of days (calculated byu datediff) in sql and the number of days in c# (calculated by DateTime.now.Substract) to be the same, but they return different results....
//returns 0
int reso = DateTime.Now.Subtract(expirationDate).Days;
vs
//returns 1
dateDiff(dd,getDate(),ExpirationDate)
In both cases, ExpirationDate is '10/1/2011 00:00:00', and the code and the DB are sitting on the same server. I want the return int to be the same. I suspect I'm missing something stupid... ideas??
dateDiff(dd,getDate(),ExpirationDate) Is doing a days comparison. DateTime.Now.Subtract(expirationDate).Days is doing a date and time
For example
SELECT dateDiff(dd,'10/1/2011 23:59:00' , '10/2/2011') returns one day even when only one minute apart.
If you want the same in C# you need to remove the time component
e.g.
DateTime dt1 = new DateTime(2011,10,1, 23,59,0);
DateTime dt2 = new DateTime(2011,10,2, 0,0,0);
Console.WriteLine((int) dt2.Subtract(dt1.Subtract(dt1.TimeOfDay)));
So in your case it would be something like
DateTime CurrentDate = DateTime.Now;
int reso = CurrentDate.Subtract(CurrentDate.TimeOfDay).Subtract(DateTime.expirationDate).Days;
I haven't tested it but I would not do
DateTime.Now.Subtract(DateTime.Now.Subtract.TimeOfDay)
Because the second call to Now wouldn't be guaranteeing to be the same as first call to Now
In any case Stealth Rabbi's answer seems more elegant anyway since you're looking for a TimeSpan not a DateTime
10/1/2011 is less than 1 day away from DateTime.Now. Since you're getting back a TimeSpan and then applying Days to it, you're getting back a TimeSpan that is < 1 day. So it'll return 0 Days.
Instead, just use the Date component of those DateTimes and it'll correctly report the number of days apart - like this:
DateTime now = DateTime.Now;
DateTime tomorrow = new DateTime(2011, 10, 1);
var val = (tomorrow.Date - now.Date).Days;
This will yield you 1 day.
I'm assuming you want the number of Total days, not the number of days from the largest previous unit. You'd want to use the TotalDays property. Also, you may find it easier to use the minus operator to do a subtraction
DateTime d1 = DateTime.Now;
DateTime d2 = new DateTime(2009, 1, 2);
TimeSpan difference = d1 - d2;
Console.WriteLine(difference.TotalDays); // Outputs (today):1001.46817997424

How can I increment a date?

I have two dates as duedate as 03/03/2011 and returndate as 03/09/2011. I want to find the fine in double when I subtract duedate from returndate.How can duedate be incremented?
Following code might help you:
var dueDate = new DateTime(2011, 3, 3);
//if you want to increment six days
var dueDatePlus6Days = dueDate.AddDays(6);
//if you want to increment six months
var dueDatePlus6Months = dueDate.AddMonths(6);
var daysDiff1 = (dueDatePlus6Days - dueDate).TotalDays; //gives 6
var daysDiff2 = (dueDatePlus6Months - dueDate).TotalDays; //gives 184
The logical solution would seem to be the AddDays method, as in the other answers.
However, I try (in general) never to use floating point (i.e. a double) when working with monetary or date values.
DateTime contains a time component and AddDays takes a double as argument (fractional part becomes time), so I tend to avoid use of that method.
Instead, I use
dueDatePlusOne = dueDate.AddTicks(TimeSpan.TicksPerDay);
This should result in slightly faster execution too. Not that it still matters much on today's hardware, but I started out coding for microprocessors with a <1 MHz clock speed and old PDP-8's and -11's and stuff like that back in the 1970's, and some habits never die ;)
Assuming returnDate, dueDate are DateTime objects:
double extraDays = (returnDate - dueDate).TotalDays;
May this can help you
DateTime dt_duedate = DateTime.Now;
DateTime dt_returndate = DateTime.Now.AddDays(2);
System.TimeSpan diffResult = dt_returndate.Subtract(dt_duedate);

Parsing times above 24 hours in C#

Suppose a time stamp (just time or date and time) where the time can roll over to the next day:
00:00:00 <- midnight
01:00:00 <- 1 AM
23:00:00 <- 11 PM
24:00:00 <- midnight, day + 1
25:00:00 <- 1 AM, day + 1
What would be a way to parse it easily into a C# DateTime that would perform the carry-over to the next day? In other words, "01:00:00" would become "0001-01-01 01:00:00" and "25:00:00" would become "0001-01-02 01:00:00".
EDIT:
I should mention that this fails miserably (i.e FormatException):
DateTime.ParseExact("0001-01-01 25:00:00", "yyyy-MM-dd HH:mm:ss", CultureInfo.InvariantCulture);
Since you're trying to represent a period of time from an arbitrary point, rather than as a specific date, perhaps you would be better off using the System.TimeSpan class? This allows you to set values of more than 24 hours in the constructor, and can be used with DateTime objects like this:
System.TimeSpan timestamp = new System.TimeSpan(25, 0, 0);
System.DateTime parsedDateTime = new DateTime(0, 0, 0);
parsedDateTime = parsedDateTime.Add(timestamp);
Console.WriteLine(parsedDateTime.ToString("yyyy-MM-dd HH:mm:ss")); //Output as "0001-01-02 01:00:00"
NOTE: Code is untested.
EDIT: In terms of parsing the strings, I can't think of any basic .NET objects that parse strings with values greater than 23 for the hour (since 25 is an invalid hour of the day), but assuming that the format is consistent, you could create a very simple string parsing routine (or even a regular expression) to read the values individually, and load the constructor manually.
If you have an existing DateTime value you can add to, you can always use a TimeSpan:
string dt = "25:00:00";
int hours = int.Parse(dt.Split(':')[0]);
TimeSpan ts = TimeSpan.FromHours(hours);
TimeSpan.Parse() doesn't work directly in this case because it complains (fair enough!) about the 25 in the hour notation.
If you want to code it out... this should be a starting point:
string dateString = "0001-01-01 25:00:00";
string[] parts = dateString.Split(' '); //now have '0001-01-01' and '25:00:00'
string datePart = parts[0]; // '0001-01-01'
string[] timeParts = parts[1].Split(':'); //now have '25', '00', and '00
DateTime initialDate = DateTime.ParseExact(datePart, "yyyy-MM-dd", CultureInfo.InvariantCulture);//use the date as a starting point
//use the add methods to get your desired datetime
int hours = int.Parse(timeParts[0]);
int minutes = int.Parse(timeParts[1]);
int seconds = int.Parse(timeParts[2]);
DateTime resultDate = initialDate.AddHours(hours)
.AddMinutes(minutes)
.AddSeconds(seconds);
Of course, it makes assumptions that the input is formatted properly and is parsable, etc..
In addition, you could definitely use timespan instead of the individual add methods for hour, minute, second as some other answers are..
In case nobody points out an out-of-the-box answer, here is a neat ActionScript class I wrote to parse time inputs (human input)...
https://github.com/appcove/AppStruct/blob/master/Flex/AppStruct/src/AppStruct/TimeInput.as
It would be very simple to port this to C#, and you could tweak the 24 hour logic to result in #days, #hours, #minutes.
Good luck!
You are specifying an invalid date. So not only can you not parse it, you cannot store it!
How about a nice TimeSpan object instead? (It also has a Parse() method.)
Alternatively, use a sscanf()-type function like the one at http://www.blackbeltcoder.com/Articles/strings/a-sscanf-replacement-for-net to extract each number separate. (Best if you have no control over the string format being read.)

Categories