1
votes

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 ?

2

2 Answers

1
votes

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);
-1
votes

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