C# convert a String to DateTime : To convert a String into a DateTime we can use the DateTime.Parse method. For example:

DateTime myDt = DateTime.Parse("2018-10-02 11:25:27.860");

Now the myDt contains a date with 02/10/2018 11:25:27 value (on italian format).

But if our string date include TimeZone informations, if we use DateTime.Parse method, we get a wrong value:

DateTime myDt = DateTime.Parse("2018-10-02T11:25:27.860Z");

Now the myDt contains a date with 02/10/2018 13:25:27 value.

If we want to ignore the TimeZone, we can use the DateTimeOffset.Parse method:

DateTimeOffset myDto = DateTimeOffset.Parse("2018-10-02T11:25:27.860Z");

Now the myDto contains a date with 02/10/2018 11:25:27 +00:00 value.

And we can use myDto.DateTime property to get the DateTime value.

Tagged:

Laisser un commentaire