how to convert string to DateTime as UTC as simple as that
I did this by checking the DateTimeKind
. On my function, 2 different types of date-times are coming. What I want is to convert UTC time to local time from the below function. Input parameter date
is always coming as UTC.
Eg inputs: 2021-01-19 07:43:00 AM
and 01/07/2021 02:16:00 PM +00:00
public static DateTime GetDateTime(string date)
{
try
{
DateTime parsedDate = DateTime.Parse(date, GetCulture()); //invarient culture
if (parsedDate.Kind == DateTimeKind.Unspecified)
{
parsedDate = DateTime.SpecifyKind(parsedDate, DateTimeKind.Utc);
}
return parsedDate.ToLocalTime();
}
catch (Exception e)
{
throw;
}
}
The accepted answer did not work for me. Using DateTimeOffset.Parse(string)
or DateTimeOffset.ParseExact(string)
with the .UtcDateTime
converter correctly changed the kind of the DateTime
to UTC, but also converted the time.
To get to a DateTime
that has the same time as the original string time, but in UTC use the following:
DateTime dt = DateTime.ParseExact(string, "yyyy-MM-ddTHH:mm:ss.fffffff",
CultureInfo.InvariantCulture);
dt = DateTime.SpecifyKind(dt, DateTimeKind.Utc);
Use DateTimeOffset.Parse(string).UtcDateTime
.