Reputation: 59
I have a problem using SpecifyKind.
I discoverd that if I apply Tostring("O") to DateTime.Now or to new DateTime() , I will have the spantime different . I dont undrestand how it is possible. I try to save these datetimes as Utc in database, but the fact that span is different , the times will not be correct.
This is what i do:
var now = DateTime.Now;
var nowst = now.ToString("O", CultureInfo.InvariantCulture);
var dattt = new DateTime(2020,07,20,09,44,09, DateTimeKind.Local);
var datttst = dattt.ToString("O", CultureInfo.InvariantCulture);
now: 2021-12-08 13:40:35 nowst: 2021-12-08T13:40:35.1159209+01:00 dattt : 2020-07-20 09:44:09 datttst :2020-07-20T09:44:09.0000000+02:00"
Upvotes: 0
Views: 86
Reputation: 6159
When saving to DB you want to save the UTC date-time in order to avoid the time difference as you already mentioned, but the better way to do it in C# is using the UtcNow, the "O" value is just to get the ISO-8601 representation of the value. If your time is already in UTC, you won't get that +GMT addition to the ISO-8601 string.
var utcNow = DateTime.UtcNow;
var utcNowO = utcNow.ToString("O", CultureInfo.InvariantCulture);
Console.WriteLine($"DateTime UtcNow: {utcNow} =>ISO-8601 of it: {utcNowO}");
As to why the difference in the values in your question, it is the daylight saving time, if you pick UtcNow you can completely ignore it and save the value to the db. When reading from the DB you can convert it to the local time again which will take into consideration the GMT for the local time zone.
As to daylight-saving-time - that cannot be taken into consideration out of the box since these can be arbiter decisions made by governments. i.e. In Israel - less than a month ago the government passed a decision to set the clock to GMT+3 to adjust to daylight, it always been GMT+2 till then for many years.. your code executing in the future won't know that such a decision happened in the past for just few months out of the box.
If you want your code to "know" that in the future you should save the local time with the time difference instead of the UTC date time.
Upvotes: 1