Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)

like image 753
user1025852 Avatar asked Nov 06 '12 15:11

user1025852


People also ask

How do you convert date to UTC format?

To convert a JavaScript date object to a UTC string, you can use the toUTCString() method of the Date object. The toUTCString() method converts a date to a string, using the universal time zone. Alternatively, you could also use the Date. UTC() method to create a new Date object directly in UTC time zone.

How do you convert string to UTC time in python?

Python convert a string to datetime with timezone In this example, I have imported a module called timezone. datetime. now(timezone('UTC')) is used to get the present time with timezone. The format is assigned as time = “%Y-%m-%d %H:%M:%S%Z%z”.

How do I convert a string to a date?

Using strptime() , date and time in string format can be converted to datetime type. The first parameter is the string and the second is the date time format specifier. One advantage of converting to date format is one can select the month or date or time individually.

What is UTC time string?

Times are expressed in UTC (Coordinated Universal Time), with a special UTC designator ("Z"). Times are expressed in local time, together with a time zone offset in hours and minutes. A time zone offset of "+hh:mm" indicates that the date/time uses a local time zone which is "hh" hours and "mm" minutes ahead of UTC.


2 Answers

Use DateTimeOffset.Parse(string).UtcDateTime.

like image 133
Knaģis Avatar answered Oct 17 '22 15:10

Knaģis


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);
like image 25
Snympi Avatar answered Oct 17 '22 16:10

Snympi