How can I prevent negative time in using military time format - c#

when my starttime = "19:00" PM then my endtime ="01:30" AM
the answer is negative , how can i prevent negative result in time?
string startime = record.TimeStart;
string endtime = record.TimeFinish;
TimeSpan span = DateTime.Parse(endtime).Subtract(DateTime.Parse(startime));
string hours_spent = string.Format(
"{0:D2}:{1:D2}:{2:D2}",
span.Hours, span.Minutes, span.Seconds);

You are crossing midnight, so the actual comparison is (using today's date as an example):
[2015-10-12 01:30] - [2015-10-12 19:00]
which is -17 hrs and 30 minutes. If you want to convert that to a positive time then either add a date component or add 24 hours to the time span:
if(span.Hours < 0)
span = span.AddDays(1);

Add one day to endtime if it (or more precisely, its time component) is earlier than starttime's. Something like this:
var startDateTime = DateTime.Parse(starttime).Time;
var endDateTime = DateTime.Parse(endtime).Time;
if (endDateTime < startDateTime)
{
endDateTime += TimeSpan.FromDays(1);
}
TimeSpan timeSpent = endDateTime - startDateTime;

Related

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.

Timespan between (2) other Timespan when adding / subtracting minutes C#

Everything works with the exception if I pass in "15 minutes". I receive no errors, it's just that my where clause isn't working 100%. This is b/c I pass in time in 15 minute intervals.
Example:
Object 1 has a time of 00:20 (12:20 am) (24hr format)
Object 2 has a time of 02:15 (02:15 am) (24hr format)
The parsedTime param is a javascript 24hr format time - in this example is comes in as "00:15".
The problem is when I subtract the -30 minutes from the parsedTime, it puts it at 23:45, and therefore never gets the "00:20".
LINQ query
DateTime parsedTime = DateTime.ParseExact(time, "HH:mm", CultureInfo.InvariantCulture);
var activities = objects
.Where(x => (x.GetValue<DateTime>("startTime").TimeOfDay
>= parsedTime.AddMinutes(-30).TimeOfDay
&& x.GetValue<DateTime>("startTime").TimeOfDay
<= parsedTime.AddMinutes(30).TimeOfDay))
.ToList();
You just want to see if they're within 30 minutes of each other, right? Try using actual timespans
DateTime startTime;
DateTime parsedTime;
TimeSpan difference = startTime - parsedTime;
return difference.TotalMinutes < 30 && difference.TotalMinutes > -30;
It sounds like you also need to handle time ranges that could span across midnight, as in the 30 minutes that exists between "23:45" and "00:15". Here's how you can do that:
public static TimeSpan GetTimeDifference(string startTimeOfDay, string endTimeOfDay)
{
DateTime startDateTime = DateTime.ParseExact(startTimeOfDay, "HH:mm",
CultureInfo.InvariantCulture, DateTimeStyles.NoCurrentDateDefault);
DateTime endDateTime = DateTime.ParseExact(endTimeOfDay, "HH:mm",
CultureInfo.InvariantCulture, DateTimeStyles.NoCurrentDateDefault);
if (endDateTime >= startDateTime)
{
// values do not cross over midnight
return endDateTime - startDateTime;
}
else
{
// values cross over midnight
return endDateTime - startDateTime + TimeSpan.FromHours(24);
}
}
Or if you prefer something smaller:
public static int GetMinutesDifference(string startTimeOfDay, string endTimeOfDay)
{
DateTime startDateTime = DateTime.ParseExact(startTimeOfDay, "HH:mm",
CultureInfo.InvariantCulture, DateTimeStyles.NoCurrentDateDefault);
DateTime endDateTime = DateTime.ParseExact(endTimeOfDay, "HH:mm",
CultureInfo.InvariantCulture, DateTimeStyles.NoCurrentDateDefault);
return (((int)(endDateTime - startDateTime).TotalMinutes + 1440) % 1440);
}

Date comparison - How to check if 20 minutes have passed?

How to check if 20 minutes have passed from current date?
For example:
var start = DateTime.Now;
var oldDate = "08/10/2011 23:50:31";
if(start ??) {
//20 minutes were passed from start
}
what's the best way to do this?
Thanks :)
You should convert your start time to a UTC time, say 'start'.
You can now compare your start time to the current UTC time using:
DateTime.UtcNow > start.AddMinutes(20)
This approach means that you will get the correct answer around daylight savings time changes.
By adding time to the start time instead of subtracting and comparing the total time on a TimeSpan you have a more readable syntax AND you can handle more date difference cases, e.g. 1 month from the start, 2 weeks from the start, ...
var start = DateTime.Now;
var oldDate = DateTime.Parse("08/10/2011 23:50:31");
if ((start - oldDate).TotalMinutes >= 20)
{
//20 minutes were passed from start
}
var start = DateTime.Now;
var oldDate = DateTime.Parse("08/10/2011 23:50:31");
if(start.Subtract(oldDate) >= TimeSpan.FromMinutes(20))
{
//20 minutes were passed from start
}
Parse oldDate into a DateTime object (DateTime.Parse).
Subtract the parsed date from start. This will return a TimeSpan.
Inspect TotalMinutes.
I was able to accomplish this by using a JodaTime Library in my project. I came out with this code.
String datetime1 = "2012/08/24 05:22:34";
String datetime2 = "2012/08/24 05:23:28";
DateTimeFormatter format = DateTimeFormat.forPattern("yyyy/MM/dd HH:mm:ss");
DateTime time1 = format.parseDateTime(datetime1);
DateTime time2 = format.parseDateTime(datetime2);
Minutes Interval = Minutes.minutesBetween(time1, time2);
Minutes minInterval = Minutes.minutes(20);
if(Interval.isGreaterThan(minInterval)){
return true;
}
else{
return false;
}
This will check if the Time Interval between datetime1 and datetime2 is GreaterThan 20 Minutes. Change the property to Seconds. It will be easier for you know. This will return false.
var end = DateTime.Parse(oldDate);
if (start.Hour == end.Hour && start.AddMinutes(20).Minute >= end.Minute)

Calculate time difference in c# windows phone 7

I am trying to calculate the time difference between 2 time and put the result into a text block.
For example,
Start time: 9:45 AM
End start: 5:15 PM
How can i calulate the time difference between it?
DateTime dt1 = DateTime.ParseExact(DateTime.Now.ToShortTimeString(), "hh:mm tt", new DateTimeFormatInfo());
DateTime dt2 = DateTime.ParseExact(timePicker1.ValueString, "hh:mm tt", new DateTimeFormatInfo());
TimeSpan ts1 = dt2.Subtract(dt1);
For time "11:12 PM" you should use format "h:mm tt". So, you parse two time strings and make Subtract or just (dateTime1 - dateTime2).
try:
DateTime dt1 = DateTime.ParseExact("22:22:22", "HH:mm:ss", new DateTimeFormatInfo());
DateTime dt2 = DateTime.ParseExact("11:11:11", "HH:mm:ss", new DateTimeFormatInfo());
TimeSpan ts1 = dt1.Subtract(dt2);
protected void Page_Load(object sender, EventArgs e)
{
// Declare and get DateTime values
DateTime StartDate = System.DateTime.Now;
DateTime EndDate = System.DateTime.UtcNow;
// Find time difference between two dates
TimeSpan TimeDifference = StartDate - EndDate;
// Write difference in hours and minutes
Response.Write("Time difference between server time and Coordinated Universal Time (UTC) is " +
TimeDifference.Hours.ToString() + " hours ");
if (TimeDifference.Minutes != 0)
Response.Write(" and " + TimeDifference.Minutes.ToString() + " minutes.");
}
or try
/* Read the initial time. */
DateTime startTime = DateTime.Now;
Console.WriteLine(startTime);
/* Do something that takes up some time. For example sleep for 1.7 seconds. */
Thread.Sleep(1700);
/* Read the end time. */
DateTime stopTime = DateTime.Now;
Console.WriteLine(stopTime);
/* Compute the duration between the initial and the end time.
* Print out the number of elapsed hours, minutes, seconds and milliseconds. */
TimeSpan duration = stopTime - startTime;
Console.WriteLine("hours:" + duration.Hours);
Console.WriteLine("minutes:" + duration.Minutes);
Console.WriteLine("seconds:" + duration.Seconds);
Console.WriteLine("milliseconds:" + duration.Milliseconds);
The method suggested by O.D. is what I use in my app that uses a time difference. I then use the method ng_ducnghia suggests to separate units of time (hours, min, sec - I don't need millisec for my purpose).

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