Common DatetimeOffset usage with C#
Jan 08 2024 11:30
The DateTimeOffset structure includes a DateTime value, together with an Offset property that defines the difference between the current DateTimeOffset instance's date and time and Coordinated Universal Time (UTC)
It represents dates and times with values whose UTC ranges from 12:00:00 midnight, January 1, 0001 Anno Domini (Common Era), to 11:59:59 P.M., December 31, 9999 A.D. (C.E.).
How to use DateTimeOffset
Create DateTimeOffset object
DateTimeOffset = DateTime + Offset path, so usage is similar to DateTime
DateTimeOffset today = new DateTimeOffset();
Console.WriteLine(today); // 01/01/0001 00:00:00 +00:00
today.Should().Be(DateTimeOffset.MinValue); // True
// Local time of machine 8 Jan 2024 10:08
today = DateTimeOffset.Now;
Console.WriteLine(today); 08/01/2024 10:07:16 +07:00
+00:00 and + 07:00 is offset specific part
Create DateTimeOffset object
var today = new DateTimeOffset(2024, 1, 1, 11, 30, 00, new TimeSpan(7, 0, 0));
Console.WriteLine(today); // 01/01/2024 11:30:00 +07:00
Console.WriteLine(DateTimeOffset.Now); // Local machine Vietnam UTC+7 time 08/01/2024 11:40:38 +07:00
Console.WriteLine(DateTimeOffset.UtcNow); // Basis of utc time (UTC or UTC+0) 08/01/2024 04:40:38 +00:00
Format DateTimeOffset object
Sample UTC time in ISO-8601 format: 2024-01-01T12:12:34+00:00 Format pattern: "dd-MM-yyyy HH:ss:mmzzz"
Console.WriteLine(DateTimeOffset.UtcNow.ToString("dd-MM-yyyy HH:ss:mmzzz")); // 08-01-2024 04:43:48 +00:00
More format patterns sample at https://learn.microsoft.com/en-us/dotnet/standard/base-types/custom-date-and-time-format-strings
Parse UTC time from ISO-8601 string
var utcTimeString = "2024-01-01T11:30:00+07:00";
var utcTime = DateTimeOffset.ParseExact(utcTimeString, "yyyy-MM-ddTHH:ss:mmzzz", CultureInfo.InvariantCulture);
// Format ISO-8061 to better readable pattern
Console.WriteLine(utcTime.ToString("dd-MM-yyyy HH:ss:mm zzz")); // 01-01-2024 11:30:00 +07:00
Code example at: Github
Delete comment
Confirm delete comment
Pham Duc Minh
Da Nang, Vietnam