How to get Difference hours Between two date - c#

I want get diffrences Day,Hour and Day between two days.
I use belowe Code :
DateTime LastDate = DateTime.Parse("2/12/2015 11:24:23 AM");
int differenceDay = DateTime.Now.Subtract(LastDate).Days;
int differenceHoure = DateTime.Now.Hour - LastDate.Hour;//returns -11
int differenceMinute = DateTime.Now.Minute - LastDate.Minute;
When I want get Hours its return mines (-11 e.t).
How can I get positive Diffrence Hour ?
anyone can you help me?
I want get Last Dat and show its by string how days afterd now.

You're subtracting component-wise (i.e. "this hour-of-day minus that hour-of-day, this minute-of-hour minus that minute-of-hour"). Don't do that - it won't work if the current hour-of-day is earlier than the hour-of-day of lastDate, or the same for minute-of-hour - you get a negative value, exactly as you've seen.
Instead, subtract one DateTime from another to get a TimeSpan and use that single TimeSpan for all the components:
DateTime lastDate = DateTime.Parse("2/12/2015 11:24:23 AM");
TimeSpan difference = DateTime.Now - lastDate;
int days = difference.Days;
int hours = difference.Hours;
int minutes = difference.Minutes;
That will still be negative if lastDate is after DateTime.Now, of course.
Note that this will give you a result which is meaningful if you display all three components. For example, it might give you "2 days, 3 hours and 10 minutes". If instead you want to represent the same TimeSpan as "2.194 days" or "51.166 hours" or "3160 minutes" then you can use TotalDays, TotalHours and TotalMinutes.
If you always want a positive TimeSpan - the equivalent of Math.Abs but for TimeSpan you can just use TimeSpan.Duration():
TimeSpan difference = (DateTime.Now - lastDate).Duration();

Related

Sum times over 24:00 in C#

I want to collect a few hours, but if sum is over 24:00 I take as like it: 1.01:20
How can it in c#:
23:00 + 02:00 = 25:00 ?
Best regards
What has this question to do with Mysql at all? You are asking about the sum of multiple C# TimeSpan, aren't you? Then TotalHours might give you the answer:
TimeSpan ts = TimeSpan.FromHours(23);
ts = ts + TimeSpan.FromHours(2);
int hours = (int) ts.TotalHours;
If you want the sum as formatted string "25:00", use this approach:
string hourMinute = $"{((int)ts.TotalHours).ToString("D2")}:{ts.Minutes.ToString("D2")}";
The ToString("D2") ensures that you always have at least two digits for the hours and minutes, with a leading zero if necessary. Read: Standard numeric format strings

Get Random Date with hours and minutes from now until 2 days ago

Hi How Can I get a random date with hours and minutes in a range bewtween now and 2 or 3 days ago. ??
Thanks to all
something like this dates time with minutes
10/23/2018 4:32:00 PM
10/23/2018 5:31:00 PM
10/23/2018 1:32:00 AM
10/22/2018 2:00:00 PM
Here I can get the dates in a range, let say 2 days, but the hour is the same
public static DateTime NextDateTime(int endDatenumbers)
{
DateTime startDate = DateTime.Today;
DateTime endDate = startDate.AddDays(-endDatenumbers);
var newDate = startDate.AddHours(new Random(Convert.ToInt32(DateTime.Now.Ticks / int.MaxValue)).Next(0, (int)(endDate - startDate).TotalHours));
return newDate;
}
You should simplify that to 1 random call.
Get the furthest day which is 3 days ago.
var furthestDate= DateTime.Today.AddDays(-3);
You range is actually 2 days after that date which is (48hrs * 60 min) = 2880 minutes.
So anything from that date and 2880 minutes after is valid.
Simply get 1 random number between 0 an 2880. Finally simply add the minutes to the furthest date.
var randomDate = furthestDate.AddMinutes(YouRandomNumber);
The following logic actually computes the number of minutes between the two days. This is important where your days can potentially cross a daylight savings boundary. Also, I am storing the value "today" as technically (albeit unlikely) it could change between the two calls.
private static DateTime PickRandomMinute(int inPastNDays, Random random)
{
DateTime today = DateTime.Today;
int totalMinutes = (int)(today - today.AddDays(-inPastNDays)).TotalMinutes;
return today.AddDays(-inPastNDays).AddMinutes(random.Next(totalMinutes));
}
Example usage:
Random random = new Random();
Console.WriteLine(PickRandomMinute(2, random)); // 22/10/2018 9:34:00 PM (for example)
Console.WriteLine(PickRandomMinute(2, random)); // 23/10/2018 4:55:00 AM (for example)
You don't want to create a new Random within this method because calls that happen very close together would probably end up with the same seed and therefore return the same time.

If condition not working as expected c#

This is now bugging me , i have tried to fix it for the past hour but still no luck!
I hope some one could spot what i'm doing wrong . here is my code:
var maxDays = 30;
DateTime today = DateTime.Now; //todays date
DateTime lastAction = '2017-03-07 12:47:58.967';
double totalDays = (lastAction - today).TotalDays;
var days = Math.Round(totalDays);
if(days > maxDays)
{
//never hits this even though days is greater than max days ..i'm so confused
}
what am i doing wrong?
Duplicate problem as here:
C# Number of days between two dates problem
Timespan.TotalDays can be negative. So in your case it is almost guaranteed that lastAction - today will be a negative number, and so will always be less than 30.
If you only care about the absolute value of days, use Math.Abs otherwise re-arrange so that you are subtracting lastAction from today (today - lastAction).
Note that due to rounding, your condition will still not be triggered if there is less than 1 day difference.
Is it possible you are subtracting a larger value (today) from a small value (lastaction) which should result in a negative number making days negative?
That and you do need to do an explicit parse on the string to make it a date:
DateTime lastAction = DateTime.Parse("2017-03-07 12:47:58
.967");
Couple of things.
First you cant convert a string to DateTime like that. You should do something like this instead. DateTime lastAction = DateTime.Parse("2017-03-07 12:47:58.967");
Second, Just as #MikeS said, you are subtracting the lastAction from Today, which is resulting in a negative number (in this case its like -173). You should flip that statement. double totalDays = ( today - lastAction).TotalDays;
Your whole section should look something like this.
var maxDays = 30;
DateTime today = DateTime.Now; //todays date
DateTime lastAction = DateTime.Parse("2017-03-07 12:47:58.967");
double totalDays = ( today - lastAction).TotalDays;
var days = Math.Round(totalDays);
if (days > maxDays)
{
// now this is hit
}
Thanks for the help. I did something stupid .. I had
double totalDays = (lastAction - today).TotalDays; // returns -176
changed my code to:
double totalDays = (today - lastAction).TotalDays; //returns 176
Your first problem:
You didn't parse the string to DateTime.
DateTime lastAction = Convert.ToDateTime("2017-03-07 12:47:58.967");
Your second problem:
You were receiving a negative value, and checking if it's bigger.
var days = (Math.Round(totalDays)) * (-1);
Like this, it should work.

Calculating the Number of Days between two Dates and displaying it in a Label

Hi I'm trying to capture two dates selected by the user in a C# Calendar Control and I want the date range to be displayed in a label. I have worked out on the following code but it generates a Minus value ; not the actual date range.
DateTime from = CalFrom.SelectedDate;
DateTime to = CalTo.SelectedDate;
double days = (CalTo.SelectedDate - CalFrom.SelectedDate).TotalDays;
TimeSpan t = to - from;
double noOfDays = t.TotalDays;
TimeSpan ts = to - from;
double differnceindays = ts.TotalDays;
lblNoofDays.Text = differnceindays.ToString();
This code is working perfectly for me for calculating the number the days between two days.
DateTime d1 = DateTime.Now;
DateTime d2 = DateTime.Now.AddDays(10);
TimeSpan difference = d2 - d1;
var days = difference.TotalDays;
DateTime.Now.Subtract(startDate).Days.ToString();
try to calculate no of days between two dates
string days = (date2 - date1).Value.Days.ToString();
The only problem I see is that you assume the start and end dates will be correctly range checked, meaning start date is never greater than end date (which would produce negative values for total days). If you want to correct for the fact that start date may be after end date, then this should work.
DateTime startDate = DateTime.Now.AddDays(-94); // Example random 94 day span..
DateTime endDate = DateTime.Now;
TimeSpan duration = endDate > startDate ? endDate - startDate : startDate - endDate;
double daysBetweenDates = duration.TotalDays;
Note: "daysBetweenDates" will include fractional days (thus the double type). Also, the code above assumes local time. If you want UTC you will need to account for that.

Time span calculation for hours and minutes in C#

The final result should display the user the time span between the start hour and the end hour.(e.g. start work at 06:30 AM and finished at 18:30 PM, the result to display should be 12 hours).
Now, I have to DateTime parameters; fromTime and toTime
Each DateTime parameter have an hour in 24 hour format, and also might have a minutes value of 30 min.
What I willing to do is to get the time span between those DateTime parameters.
For the hours I used this method:
Public TimeSpan GetHourSpan(DateTime fromTime, DateTime toTime)
{
TimeSpan fromH = TimeSpan.FromHours(fromTime.Hour);
TimeSpan toH = TimeSpan.FromHours(toTime.Hour);
TimeSpan hourTotalSpan = toH.Subtract(fromH);
return hourTotalSpan;
}
This is great, my problem is to get the time span in minutes if there is, and finally add it to the TimeSpan object to display.
If both have 30 min time span in the above way will return 0, and than I have to start check every parameter if it have a value in the min property.
Isn't there an easy way to get time span for hours and min together?
TimeSpan span = toTime - fromTime;
// Split into hours:minutes: span.Hours, span.Minutes
// Total span in hours: span.TotalHours
// Total span in minutes (hours * 60): span.TotalMinutes
If you deduct a DateTime from a DateTime, the result is a a TimeSpan. So you can simply take
TimeSpan result = toTime-fromTime;
int hours = result.Hours;
int minutes = result.Minutes;
TimeSpan span = toTime - fromTime;
public double DurationinMins(DateTime startDt, DateTime endDt)
{
var ts = endDt.Subtract(startDt);
return ts.TotalMinutes;
}

Categories

Resources