user1025852
user1025852

Reputation: 2784

how to convert string to DateTime as UTC as simple as that

assume I have this string : How can I convert it to DateTimeOffset object that will have UTC time - means -00:00 as Time Zone - even if I run it on machine on a specific timezone?

Assume String: "2012-10-08T04:50:12.0000000"

Convert.ToDateTime("2012-10-08T04:50:12.0000000" + "Z");

--> DateTime d = {10/8/2012 6:50:12 AM} and I want it to be DateTime d = {10/8/2012 4:50:12 AM} as if it will understand I want the date as simple as it comes (BTW - my machine is in timezone +02:00)

Upvotes: 34

Views: 129324

Answers (5)

Rizan Zaky
Rizan Zaky

Reputation: 4682

Using, DateTimeStyles.AssumeUniversal in DateTime.Parse(...) will do the job,

Ex:

DateTime.Parse("2023-01-02 9:26", CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal)

then the parsed datetime will be in UTC

Upvotes: 0

SurenSaluka
SurenSaluka

Reputation: 1591

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;
        }
    }

Upvotes: 1

Towhid
Towhid

Reputation: 2084

var universalDateTime = DateTime.Parse(your_date_time_string).ToUniversalTime();

Upvotes: 2

Snympi
Snympi

Reputation: 948

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

Upvotes: 9

Knaģis
Knaģis

Reputation: 21485

Use DateTimeOffset.Parse(string).UtcDateTime.

Upvotes: 91

Related Questions