Home > Software engineering >  DateTime.ParseExact to UTC value
DateTime.ParseExact to UTC value

Time:07-28

I retrieve a date and time from my web api and set it as so :

tmp = DateTime.ParseExact(dateAndTimeFromApi, "dd/MM/yyyy HH:mm:ss", null);

I need to convert this DateTime to a UTC DateTime. When I add .ToUniversalTime() it does not convert from local to UTC. My current timezone is UTC 2. So I want to get from 11am to 9am after the conversion.

How can I do this if I want to keep the "dd/MM/yyyy HH:mm:ss" format ?

CodePudding user response:

You should add a couple of DateTimeStyles (in the System.Globalization namespace) flags as the 4th parameter.

By default the resulting DateTime will have an Unsepcified DateTimeKind therefore adjustments between local and UTC will fail. - DateTimeStyles.AssumeLocal will make sure that DateTimeKind.Local is set.

The DateTimeStyles.AdjustToUniversal flag will also perform the conversion between DateTimeKind.Local and DateTimeKind.UTC

var tmp = DateTime.ParseExact("28/07/2022 10:51:25", "dd/MM/yyyy HH:mm:ss", null,
    DateTimeStyles.AssumeLocal | DateTimeStyles.AdjustToUniversal);

CodePudding user response:

DateTimeOffset.Parse(dateAndTimeFromApi "Z").UtcDateTime should work properly

  • Related