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)
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.
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”.
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.
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.
Use DateTimeOffset.Parse(string).UtcDateTime
.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With