Dates and times
Dates are full of traps — leap years, the end of the month, time zones, a "03/04" that means two different days. This lesson uses DateOnly, TimeOnly, DateTimeOffset and TimeSpan to make date calculations that do not break.
What you will learn#
DateOnlyandTimeOnly: say in the type that you have only a date, or only a time,TimeSpan: the length between two moments,DateTimeOffset: a moment together with its distance from UTC,- what
AddMonthsandAddYearsdo at the end of a month, - counting days and computing an age,
- reading a date with an exact format.
The tutorial Numbers, dates and times made DateTime values and the tutorial Time zones converted between time zones. This lesson adds the types that make a program clearer and safer.
The program#
# dates and times - DateOnly, TimeOnly, DateTimeOffset, TimeSpan and calculations that do not break
load "dotnet.ring"
using {
"System"
"System.Globalization"
}
func main
# 1. DateTime mixes a date and a time. When you only need ONE of them, DateOnly and TimeOnly say it in the type: a birthday has no
# time, an opening hour has no date.
oDate = makeDate(2024,2,28)
? "1. a date: " + oDate.Format("yyyy-MM-dd") + ", " + oDate.DayOfWeek + ", day " + oDate.DayOfYear + " of the year"
oNextDay = oDate.AddDays(2)
? " 2 days later: " + oNextDay.Format("yyyy-MM-dd") + " (2024 is a leap year: February has 29 days)"
oTime = new TimeOnly().@New([ :hour = 22, :minute = 30, :second = 0 ])
? " a time: " + oTime.Format("HH:mm") + ", 3 hours later: " + oTime.AddHours(3).Format("HH:mm") + " (it goes round the clock: no date to move to)"
# 2. TimeSpan: the length of time between two moments. Subtracting two dates gives one.
oStart = makeDateTime(2024,3,1,8,0)
oEnd = makeDateTime(2024,3,3,17,30)
oSpan = oEnd.Subtract(oStart)
? nl + "2. from the start to the end: " + oSpan.Days + " days, " + oSpan.Hours + " hours, " + oSpan.Minutes + " minutes"
? " in total: " + oSpan.TotalHours + " hours, " + oSpan.TotalMinutes + " minutes"
oHour = new TimeSpan().FromMinutes(135)
? " 135 minutes is " + oHour.ToString() + " (hours:minutes:seconds)"
# 3. DateTimeOffset: a moment WITH its distance from UTC. Two offsets, one moment: they are equal, and UtcDateTime shows it.
oCairo = new DateTimeOffset().@New([ :year = 2024, :month = 6, :day = 15, :hour = 12, :minute = 0, :second = 0, :offset = new TimeSpan().FromHours(3) ])
oLondon = new DateTimeOffset().@New([ :year = 2024, :month = 6, :day = 15, :hour = 10, :minute = 0, :second = 0, :offset = new TimeSpan().FromHours(1) ])
? nl + "3. Cairo " + oCairo.Format("yyyy-MM-dd HH:mm zzz")
? " London " + oLondon.Format("yyyy-MM-dd HH:mm zzz")
? " they are the same moment: " + oCairo.Equals(oLondon) + ", in UTC: " + oCairo.UtcDateTime.Format("HH:mm")
# 4. Adding months: the end of the month does not exist in every month, so .NET moves to the last day that does
oJan31 = new DateTime(2024,1,31)
? nl + "4. 31 January + 1 month: " + oJan31.AddMonths(1).Format("yyyy-MM-dd") + " (29 February)"
? " 31 March + 1 month: " + new DateTime(2024,3,31).AddMonths(1).Format("yyyy-MM-dd") + " (30 April)"
? " 29 February 2024 + 1 year: " + new DateTime(2024,2,29).AddYears(1).Format("yyyy-MM-dd")
# 5. Counting: how many days to a date, and the age of a person on a day
oBirthday = makeDate(1990,8,15)
oToday = makeDate(2024,6,15)
nAge = oToday.Year - oBirthday.Year
oThisYear = makeDate(oToday.Year,oBirthday.Month,oBirthday.Day)
if oThisYear.CompareTo(oToday) > 0 # the birthday of this year has not come yet
nAge--
ok
? nl + "5. born 1990-08-15, on 2024-06-15 the age is " + nAge
? " days between the two dates: " + (oToday.DayNumber - oBirthday.DayNumber)
# 6. Parsing a date from text with an exact format, so that 03/04/2024 can not be read as the wrong day and month
aParsed = (new DateOnly).TryParseExact([ :s = "03/04/2024", :format = "dd/MM/yyyy", :provider = new CultureInfo(""), :style = "None" ])
? nl + "6. '03/04/2024' read as day/month/year: " + aParsed[2].Format("yyyy-MM-dd") + " (the 3rd of April)"
aParsed = (new DateOnly).TryParseExact([ :s = "31/04/2024", :format = "dd/MM/yyyy", :provider = new CultureInfo(""), :style = "None" ])
? " '31/04/2024' is a date: " + aParsed[1] + " (April has 30 days)"
func makeDate nYear,nMonth,nDay
return new DateOnly(nYear,nMonth,nDay)
func makeDateTime nYear,nMonth,nDay,nHour,nMinute
return (new DateTime).@New([ :year = nYear, :month = nMonth, :day = nDay, :hour = nHour, :minute = nMinute, :second = 0 ])1. a date: 2024-02-28, Wednesday, day 59 of the year
2 days later: 2024-03-01 (2024 is a leap year: February has 29 days)
a time: 22:30, 3 hours later: 01:30 (it goes round the clock: no date to move to)
2. from the start to the end: 2 days, 9 hours, 30 minutes
in total: 57.50 hours, 3450 minutes
135 minutes is 02:15:00 (hours:minutes:seconds)
3. Cairo 2024-06-15 12:00 +03:00
London 2024-06-15 10:00 +01:00
they are the same moment: 1, in UTC: 09:00
4. 31 January + 1 month: 2024-02-29 (29 February)
31 March + 1 month: 2024-04-30 (30 April)
29 February 2024 + 1 year: 2025-02-28
5. born 1990-08-15, on 2024-06-15 the age is 33
days between the two dates: 12358
6. '03/04/2024' read as day/month/year: 2024-04-03 (the 3rd of April)
'31/04/2024' is a date: 0 (April has 30 days)This program uses a few generic functions (dnNew, dnStatic) where a class cannot be used. The lesson The generic functions explains them.
How it works#
Date and time apart#
A DateTime always has both a date and a time, so a birthday is midnight on that day and an opening hour is that hour on 1 January of year 1. Neither is true. DateOnly is a day (year, month, day) and TimeOnly a time of day, so the program cannot mix them up. DateOnly knows the DayOfWeek and the DayOfYear (the 28th of February is day 59) and AddDays goes over the end of the month and over a leap day. TimeOnly.AddHours(3) after 22:30 gives 01:30: a time of day goes round the clock and has no date to move to.
These structs have several constructors: new TimeOnly().@New([ :hour = 22, :minute = 30, :second = 0 ]) chooses one by the names of its parameters (the function makeDate does the same for dates). A method that formats with a pattern is Format("yyyy-MM-dd") (the plain ToString() has no parameters, see Core concepts).
TimeSpan#
Subtracting two DateTime values gives a TimeSpan: Days, Hours and Minutes are its parts (2 days, 9 hours and 30 minutes) while TotalHours and TotalMinutes are the whole length in one unit (57.5 hours, 3450 minutes). Mixing the two is a classic mistake: Hours never goes above 23. TimeSpan.FromMinutes(135) makes one from a number and prints as 02:15:00.
DateTimeOffset#
12:00 in Cairo (UTC+3) and 10:00 in London (UTC+1) in June are the same moment. A DateTimeOffset keeps the local time and the offset, so Equals knows they are equal and UtcDateTime gives 09:00 for both. Use it for anything that happens at a real moment — a log entry, an order, a meeting — and store it with its offset, or in UTC. A plain DateTime with no offset does not know which time zone it is in, and that is the source of many bugs (the tutorial Time zones).
The end of the month#
AddMonths(1) to 31 January cannot give 31 February, so .NET gives the last day that exists: 29 February in 2024. 31 March plus one month is 30 April. AddYears(1) to 29 February 2024 gives 28 February 2025. Remember it for a bill that is due every month on the 31st: adding one month to the previous due date drifts (31 Jan, 29 Feb, 29 Mar...); add n months to the first date instead.
Ages and counts#
An age is not the difference of the years: the birthday of this year may not have come yet. The program takes the difference of the years and then subtracts 1 if the birthday of this year is later than the day. DayNumber is the number of the day since 1 January of year 1, so the difference of two DayNumber values is the number of days between them (12 358 here).
Reading a date#
03/04/2024 is the 3rd of April in Egypt and the 4th of March in the USA. When a program reads a date that a person typed, give the exact format (TryParseExact with dd/MM/yyyy and the invariant culture) instead of trusting the culture of the computer (the tutorial Cultures). TryParseExact answers [ success, date ], and the wrong 31/04/2024 is refused because April has 30 days. The method is static, so it is called with dnStatic(type, method, [arguments]).
What you learned#
DateOnlyandTimeOnlymake the meaning clear,TimeSpanparts against totals,DateTimeOffsetis a real moment,AddMonthsgoes to the last day that exists,- how to count an age,
TryParseExactfor dates that people type.
Exercises#
- Write
lastDayOfMonth(year, month)withDateOnlyandAddMonths. - Print the next 6 due dates of a bill that is due on the 31st (add months to the first date).
- Write
daysUntil(date)that counts the days to the next birthday. - Show the same moment as a
DateTimeOffsetin three offsets.