I have a requirement to calculate the duration between two times that may span midnight.
The use case is to allow the user to set up shift plans e.g. “09:00 to 17:00” or “22:00 to 06:00” and calculate the contracted time
For “09:00 to 17:00” I can use:
LocalTime inAt = new LocalTime(9, 0);
LocalTime outAt = new LocalTime(17, 0);
var period = Period.Between(inAt, outAt);
Which results in 8 hours, the answer I am looking for.
For “22:00 to 06:00” the period returns 16 hours (regardless of the order of the parameters).
LocalTime inAt = new LocalTime(22, 0);
LocalTime outAt = new LocalTime(6, 0);
var period = Period.Between(inAt, outAt);
var period2 = Period.Between(outAt, inAt);
I am guessing that this is related to daylight saving time, unless you know the dates you cannot be sure that the answer will always the 8 hours. If the clocks go forward it would be 7, backwards would be 9.
How can I ensure that no matter what LocalTime values are used the period would disregard any daylight savings? Should I use LocalDateTime with an arbitrary date such as 2021-01-01?
Also, am I correct in using Period or should I be using Duration?
Update
This seems to work however I am still wondering if there is an eaiser way of doing it?
LocalTime inAt = new LocalTime(22, 0);
LocalTime outAt = new LocalTime(6, 0);
var period = Period.Between(inAt, outAt, PeriodUnits.Ticks);
LocalTime? midnightAdjustedTime = null;
if (period.Ticks < 0)
{
midnightAdjustedTime = LocalTime.Midnight + period;
}
var duration = Duration.FromTicks(midnightAdjustedTime?.TickOfDay ?? period.Ticks);
This has nothing to do with daylight savings - it can't do, given that everything is in terms of LocalTime. It's about negative periods.
For “22:00 to 06:00” the period returns 16 hours (regardless of the order of the parameters)
No, it doesn't. One returns 16 hours, the other returns -16 hours:
using NodaTime;
var start = new LocalTime(22, 0);
var end = new LocalTime(6, 0);
var startToEnd = Period.Between(start, end);
var endToStart = Period.Between(end, start);
Console.WriteLine(startToEnd);
Console.WriteLine(endToStart);
Output:
PT-16H
PT16H
It's not clear to me how you came to the conclusion that both returned the same value, but the fact that they don't return the same value is crucial to fixing the problem. The simple approach is just to add 1 day (24 hours) if the period is negative. The code you've got is almost right, but it can be done much simpler - and without using the Ticks unit at all:
// Note: Period.ToDuration() isn't "generally safe" due to variable lengths
// of months etc, but is okay here.
var duration = startToEnd.ToDuration();
if (duration < Duration.Zero)
{
duration += Duration.FromDays(1);
}
Console.WriteLine(duration);
Related
I have a requirement which I'm getting a little confused about. I started using NodaTime which I think is the best way to go.
I have two users, User1 and User2 both in two different timezones. They are available to meet between 2pm and 5pm for example, in their local timezones. If User2 has an offset of +2 hours from User1, then the overlap is just 1 hour. What I want to get the number of hours overlap (the actual time for User1 and User2 would be a bonus.)
All I have got so far is:
var user1TimeZone = DateTimeZoneProviders.Tzdb.GetZoneOrNull(user1timezone);
var user2TimeZone = DateTimeZoneProviders.Tzdb.GetZoneOrNull(user2timeZone);
Any thoughts on how I should even start tackling this problem?
Thanks,
Firstly, be aware that it could change each day: don't treat a time zone as a fixed offset.
Secondly, be aware that the local time specified (for each of start/end) may not even happen, or may happen twice. Work out how you want to handle ambiguous and skipped times.
For any particular day, I would just convert they users' start/end times to Instant (via ZonedDateTime) and then you can find the overlap. This does assume that any overlap happens on the same day, however... that isn't the case in reality. I'm having a meeting soon where one of the attendees is in New Zealand - it's March 14th here, but March 15th there. Accounting for that is rather trickier...
Here's code for the relatively simple case though:
using NodaTime;
using System;
class Test
{
static void Main()
{
// My availability: 4pm-7pm in London
var jon = new Availability(
DateTimeZoneProviders.Tzdb["Europe/London"],
new LocalTime(16, 0, 0),
new LocalTime(19, 0, 0));
// My friend Richard's availability: 12pm-4pm in New York
var richard = new Availability(
DateTimeZoneProviders.Tzdb["America/New_York"],
new LocalTime(12, 0, 0),
new LocalTime(16, 0, 0));
// Let's look through all of March 2017...
var startDate = new LocalDate(2017, 3, 1);
var endDate = new LocalDate(2017, 4, 1);
for (LocalDate date = startDate; date < endDate; date = date.PlusDays(1))
{
var overlap = GetAvailableOverlap(date, jon, richard);
Console.WriteLine($"{date:yyyy-MM-dd}: {overlap:HH:mm}");
}
}
static Duration GetAvailableOverlap(
LocalDate date,
Availability avail1,
Availability avail2)
{
// TODO: Check that the rules of InZoneLeniently are what you want.
// Be careful, as you could end up with an end before a start...
var start1 = (date + avail1.Start).InZoneLeniently(avail1.Zone);
var end1 = (date + avail1.End).InZoneLeniently(avail1.Zone);
var start2 = (date + avail2.Start).InZoneLeniently(avail2.Zone);
var end2 = (date + avail2.End).InZoneLeniently(avail2.Zone);
var latestStart = Instant.Max(start1.ToInstant(), start2.ToInstant());
var earliestEnd = Instant.Min(end1.ToInstant(), end2.ToInstant());
// Never return a negative duration... return zero of there's no overlap.
// Noda Time should have Duration.Max really...
var overlap = earliestEnd - latestStart;
return overlap < Duration.Zero ? Duration.Zero : overlap;
}
}
public sealed class Availability
{
public DateTimeZone Zone { get; }
public LocalTime Start { get; }
public LocalTime End { get; }
public Availability(DateTimeZone zone, LocalTime start, LocalTime end)
{
Zone = zone;
Start = start;
End = end;
}
}
If you have a server where you do that, you have to send UTC and then compare it. When you get the time on the client side you have to convert it into local. It means, that when first user wants to arrange a meeting, he sends his time into UTC to server, then when second user gets this time, he will convert it into his local time.
// First user sends UTC.
DateTime firstUserTime = DateTime.UtcNow;
// Second user gets time in his time zone.
DateTime secondUserTime = firstUserTime.ToLocalTime();
How can I get the starting and ending dates for Daylight Savings Time using Noda Time?
The function below accomplishes this task but it is horribly unwieldy and is begging for a simpler solution.
/// <summary>
/// Gets the start and end of daylight savings time in a given time zone
/// </summary>
/// <param name="tz">The time zone in question</param>
/// <returns>A tuple indicating the start and end of DST</returns>
/// <remarks>Assumes this zone has daylight savings time</remarks>
private Tuple<LocalDateTime, LocalDateTime> GetZoneStartAndEnd(DateTimeZone tz)
{
int thisYear = TimeUtils.SystemLocalDateTime.Year; // Get the year of the current LocalDateTime
// Get January 1, midnight, of this year and next year.
var yearStart = new LocalDateTime(thisYear, 1, 1, 0, 0).InZoneLeniently(tz).ToInstant();
var yearEnd = new LocalDateTime(thisYear + 1, 1, 1, 0, 0).InZoneLeniently(tz).ToInstant();
// Get the intervals that we experience in this year
var intervals = tz.GetZoneIntervals(yearStart, yearEnd).ToArray();
// Assuming we are in a US-like daylight savings scheme,
// we should see three intervals:
// 1. The interval that January 1st sits in
// 2. At some point, daylight savings will start.
// 3. At some point, daylight savings will stop.
if (intervals.Length == 1)
throw new Exception("This time zone does not use daylight savings time");
if (intervals.Length != 3)
throw new Exception("The daylight savings scheme in this time zone is unexpected.");
return new Tuple<LocalDateTime,LocalDateTime>(intervals[1].IsoLocalStart, intervals[1].IsoLocalEnd);
}
There's not a single built-in function that I am aware of, but the data is all there, so you can certainly create your own.
You're on the right track with what you've shown, but there are a few things to consider:
Normally people are interested in the end points of the intervals. By returning the start and stop of only the middle interval, you are likely getting values different than you expect. For example, if you use one of the US time zones, such as "America/Los_Angeles", your function returns the transitions as 3/9/2014 3:00:00 AM and 11/2/2014 2:00:00 AM, where you are probably expecting 2:00 AM for both.
Time zones south of the equator that use DST will start it towards the end of the year, and end it towards the beginning of the next year. So sometimes the items in the tuple might be reversed from what you expect them to be.
There are quite a lot of time zones that don't use daylight saving time, so throwing an exception isn't the best idea.
There are at least two time zones that presently have four transitions in a single year ("Africa/Casablanca" and "Africa/Cairo") - having a "break" in their DST periods for Ramadan. And occasionally, there are non-DST-related transitions, such as when Samoa changed its standard offset in 2011, which gave it three transitions in a single year.
Taking all of this into account, it would seem better to return a list of single transition points, rather than a tuple of pairs of transitions.
Also, this is minor, but it would be better form to not bind the method to the system clock at all. The year can easily be passed by parameter. Then you can use this method for non-current years if necessary.
public IEnumerable<LocalDateTime> GetDaylightSavingTransitions(DateTimeZone timeZone, int year)
{
var yearStart = new LocalDateTime(year, 1, 1, 0, 0).InZoneLeniently(timeZone).ToInstant();
var yearEnd = new LocalDateTime(year + 1, 1, 1, 0, 0).InZoneLeniently(timeZone).ToInstant();
var intervals = timeZone.GetZoneIntervals(yearStart, yearEnd);
return intervals.Select(x => x.IsoLocalEnd).Where(x => x.Year == year);
}
Also note at the end, it's important to filter just the values that are in the current year because the intervals may very well extend into the following year, or go on indefinitely.
This snippet code also help you to check a time is in daylightsavingstime or not
public static bool IsDaylightSavingsTime(this DateTimeOffset dateTimeOffset)
{
var timezone = "Europe/London"; //https://nodatime.org/TimeZones
ZonedDateTime timeInZone = dateTimeOffset.DateTime.InZone(timezone);
var instant = timeInZone.ToInstant();
var zoneInterval = timeInZone.Zone.GetZoneInterval(instant);
return zoneInterval.Savings != Offset.Zero;
}
how to use it
var testDate = DateTimeOffset.Now;
var isDst = testDate.IsDaylightSavingsTime();
Depend on your situation, you can modify it a bit
I was just wondering if there is a way to get the current time and set it into a value.
If its 12:06 AM.. I want to get that time and set it into currentTime.
Example
float currentTime = 0;
currentTime = 12.06;
As others have mentioned, the DateTime class would be ideal for this, and to work out the difference between 2 date/times:
DateTime end = DateTime.Now;
DateTime start = new DateTime(2011, 12, 5, 12, 6,0);
double hours = (end - start).TotalHours;
The subtraction of DateTime objects results in a TimeSpan object that you can use to see the hours/minutes etc.
try DateTime class
DateTime dt = DateTime.Now;
Is this what you're looking for?
DateTime currentTime;
currentTime = DateTime.Now;
Don't use floats or strings. You can do all kinds of cool things using DateTime.
Here's how you'd get the hours that someone worked:
var clockIn = new DateTime(2011,12,4,9,0,0); // December 4th, 9 AM
var clockOut = new DateTime(2011,12,4,17,0,0); // December 4th, 5 PM
var duration = clockOut - clockIn; // TimeSpan
Console.Write(duration.TotalHours); // 8
A few people have mentioned how, but as a 'better' recommendation you should use
DateTime currentTime = DateTime.UtcNow
Otherwise you have issues when the clocks go back, if your timing code is run on those days. (plus it is far easier to alter the UTC time to local time than it is to convert a '1am' to UTC (as there will be two of them when the clocks go back)
Well if you really what it as a float then try:
var currentDate = DateTime.Now;
float currentTime = float.Parse((currentDate.Hour > 12 ? currentDate.Hour -12 :
currentDate.Hour) + "." + currentDate.Minute);
I wouldn't recommend comparing dates or time with floats. A better options would be to use timespans.
You should be using a Timespan instance for time related values, you can use the flexibility to get the required values like
TimeSpan ts = DateTime.Now.TimeOfDay;
ts.ToString("hh:mm") // this could be what you are looking for
You could then use ts.TotalHours which would give you fractional hours (as a double) else you could construct a string specifically using ts.Hours ..ts.Minutes play around and it could be prove useful.
Try the following:
DateTime StartTime=StartTime value;
DateTime CurrentTime=DateTime.Now;
TimeSpan dt = CurrentTime.Subtract(StartTime);
In dt you will get a working time period.
If you want to have the difference between two times, then do this:
DateTime dateOne = DateTime.Parse(enteredTime);
DateTime dateTwo = DateTime.Now;
TimeSpan difference = dateOne - dateTwo;
It is 8:30 and I am trying to find out how many seconds there are between now and the next whole hour (9:00). I think I just want to DateTime.Now.AddHours(1) but after I do that I think I need the "floor". How to get that value?
Thanks.
Just round the time of day in hours up to the next integral value:
var timeOfDay = DateTime.Now.TimeOfDay;
var nextFullHour = TimeSpan.FromHours(Math.Ceiling(timeOfDay.TotalHours));
var delta = (nextFullHour - timeOfDay).TotalSeconds;
//Completely misread. Completely re-writing
I woudl just do something Like this
int minutesToNextHour = 60 - DateTime.Now.Minutes;
int secondsToNextHour = minutesToNextHour * 60;
You don't have to mess around with ceilings and floors. The DateTime.Hour property represents whole hours (it is an integer beteen 0 and 23) of the time of the day represented by the DateTime. You can use this and the DateTime.Date property to strip the components of the DateTime you don't want (sub-hour data) and then just subtract as necessary to produce a TimeSpan.
var now = DateTime.Now;
var timeToNextHour = now.Date.AddHours(now.Hour + 1) - now;
You can of course extract the TotalSeconds component of the resulting TimeSpan if you want the result in seconds.
This seems to be the most simple:
3600 - DateTime.Now.TimeOfDay.TotalSeconds % 3600
(if you want it in whole numbers - integer - then prefix DateTime.Now... with (int).
So you'd need to subtract the 'remainder' minutes, find the difference, and multiply that by 60, right?
How about this:
var currentTime = DateTime.Now;
var hour = currentTime.AddHours(1).Hour;
var newTime = Convert.ToDateTime(hour + ":00");
var timespan = newTime.Subtract(currentTime);
var secondsDiff = timespan.TotalSeconds;
TimeSpan sec = new TimeSpan(0, 0, 3600 - (DateTime.Now.Minute * 60));
How about:
var now = DateTime.Now;
int secondsTillNextHour = (60 - now.Minute)*60+(60-now.Second);
Or (maybe clearer):
int SecondsTillNextHour = 3600 - 60*now.Minute - now.Second;
A more readable version:
public double SecondsToNextHour()
{
return SecondsToNextHour( DateTime.Now );
}
public double SecondsToNextHour( DateTime moment )
{
DateTime currentHour = new DateTime( moment.Year, moment.Month, moment.Day, moment.Hour, 0, 0 );
DateTime nextHour = currentHour.AddHours( 1 );
TimeSpan duration = nextHour - moment;
return duration.TotalSeconds;
}
TimeSpan result = (new DateTime(DateTime.Now.Year, DateTime.Now.Month,
DateTime.Now.Day, DateTime.Now.Hour + 1, 0, 0)).Subtract(DateTime.Now);
Basically here you are building a new DateTime that is one hour on from Now, with no minutes or seconds, then you subtract Now from this and have your result.
I would Timespan.Parse 08:30, add 1 hr to the object, then retrieve the hour part and build a new string with :00 as the minutes and reparse the new string. There may be a more efficient way to do this, but I find this technique clear to read.
i am doing a project on cab services.in this rate is different for day and night.
in the form only journey start date and end date is selected.based on this i have to calculate the no of days and nights.
here i am confused how to calculate the no of days and night.
thanks in advance.
private List<DateTime> GetDateRange(DateTime StartingDate, DateTime EndingDate)
{
if (StartingDate > EndingDate)
{
return null;
}
List<DateTime> rv = new List<DateTime>();
DateTime tmpDate = StartingDate;
do
{
rv.Add(tmpDate);
tmpDate = tmpDate.AddDays(1);
} while (tmpDate <= EndingDate);
return rv;
}
To view this code in action, copy and paste the following code into SnippetCompiler:
DateTime StartingDate = DateTime.Parse("02/25/2007");
DateTime EndingDate = DateTime.Parse("03/06/2007");
foreach (DateTime date in GetDateRange(StartingDate,EndingDate))
{
WL(date.ToShortDateString());
}
Sample output :
2/25/2007
2/26/2007
2/27/2007
2/28/2007
3/1/2007
3/2/2007
3/3/2007
3/4/2007
3/5/2007
3/6/2007
Use the Subtract method to get the difference, which is a TimeSpan value. Example:
TimeSpan diff = SecondDate.Subtract(FirstDate);
You can get the length of the time span for example in hours:
double hours = diff.TotalHours;
I'm not sure which time unit "days and nights" could be interpreted as, though. Perhaps days?
double days = diff.TotalDays;
DateTime dt1,dt2;
//...
TimeSpan period = dt1 - dt2;
int days = period.Days;
It sounds like a very long Cab journey that takes days and nights!
I think you need to define what a day and a night is more clearly in order to get your perfect answer. You also need to think about what impact Daylight Saving Time has on your calculations.
If say:
a day was the period from 6am to 6pm
the night was the rest - from 6pm to 6am
and you wanted to really count hours rather than days
In this case then a calculation would require you to:
iterate a currentDateTime from the startDateTime to the endDateTime
choose the increment in the currentDateTime so that it jumps to the next time barrier (6am, 6pm or the endDateTime)
within each loop, then add to your cumulative calculation of numDayHours or numNightHours so far.
Note that:
you could make this calculation quicker by counting whole days along the way
you need to be very careful about the time zone you are calculating in (I just hope that your taxi doesn't cross time zone boundaries!)
you need to be very careful about local time changes - especially "daylight savings time" type changes - the duration from 6pm to 6am is not always 12 hours!
Some pseudo code:
var numDayHours = 0.0;
var numNightHours = 0.0;
var current = startDateTime;
while (current < endDateTime)
{
next_hop = calculate_next_hop (current, endDateTime);
// select next date time
switch (next_hop.hop_type)
{
case HopType.night_time_hop:
numNightHours += next_hop.num_hours;
break;
case HopType.day_time_hop:
numDayHours += next_hop.num_hours;
break;
}
current = next_hop.EndDateTime;
}
// and here is the result
double numDays = numDayHours / 12.0;
double numHours = numNightHours / 12.0;