C # syntax date time with correct timezone and view

I have a datetime in the database that I read using SqlDataReader and then pass it to (DateTime). After casting its property Kind DateTimeKind.Unspecified.

Then I have another line that I am reading from another source. Its format is as follows: 2016-01-20T22:20:29.055Z. I do DateTime.Parse("2016-01-20T22:20:29.055Z"), and his Kind property is DateTimeKind.Local.

How to analyze both days for comparison? Do I need to use DateTimeOffsets? How to disassemble it?

thanks

+4
source share
4 answers

SQLReader DateTimeKind, . DateTime.SpecifyKind, DateTimeKind SQLReader . , UTC ; DateTimeOffset , SQL.

"2016-01-20T22: 20: 29.055Z" ISO 8601 UTC; DateTime.Parse 1 . :

, Parse DateTime, DateTimeKind.Unspecified. Parse -, s :

  • s , , Kind - DateTimeKind.Local.
  • s , AdjustToUniversalflag, (UTC) - DateTimeKind.Utc.
  • s Z GMT, RoundtripKind, UTC - DateTimeKind.Utc.

. UTC gotchas .NET SQL Server Derek Fowler .

+4

2016-01-20T22:20:29.055Z ; "Z" , (UTC). , DateTime.Parse() DateTimeKind.Local, . DateTime.ParseExact .

, datetime Unspecified, , . , , "Z" , , 2016-01-20T22:20:29.055-07:00 (UTC-7).

+2

You can use something like this:

string format = "ddd dd MMM h:mm tt yyyy";
DateTime dateTime = DateTime.ParseExact(dateString, format,
    CultureInfo.InvariantCulture);

In the format variable, you can put the desired format and pass it to the ParseExact function.

Hope this helps.

0
source

The database does not have a context (offset) of the date and time. You should save it either in the datetimeoffset column or in the datetime column, but keeping utc time. And it is always better to compare two utc times.

0
source

Source: https://habr.com/ru/post/1625224/


All Articles