25

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)

user1025852
  • 2,684
  • 11
  • 36
  • 58

5 Answers5

78

Use DateTimeOffset.Parse(string).UtcDateTime.

Knaģis
  • 20,827
  • 7
  • 66
  • 80
  • 1
    Do not know if something has changed in .NET since this was asked but I had to append ToString() to the end to get this to work, but it works perfectly DateTimeOffset.Parse(string).UtcDateTime.ToString() – alemus Oct 09 '18 at 16:21
7

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);
Snympi
  • 859
  • 13
  • 18
1

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;
        }
    }
SurenSaluka
  • 1,534
  • 3
  • 18
  • 36
0
var universalDateTime = DateTime.Parse(your_date_time_string).ToUniversalTime();
Towhid
  • 1,920
  • 3
  • 36
  • 57
0

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

Rizan Zaky
  • 4,230
  • 3
  • 25
  • 39