Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting the string "20111027" to a DateTime with a timezone of GMT

Tags:

c#

datetime

I have a string in this format: "20111027", i.e. of the general format: "yyyyMMdd".

How do I convert this to a DateTime having the timezone GMT?

This code does some conversion, but it's unclear what timezone would be used:

DateTime date = DateTime.ParseExact(dateString, "yyyyMMdd",
                               CultureInfo.InvariantCulture);
like image 307
Enchilada Avatar asked Dec 06 '25 10:12

Enchilada


1 Answers

Use a DateTimeStyles of AssumeUniversal:

DateTime date = DateTime.ParseExact(dateString, "yyyyMMdd",
                                    CultureInfo.InvariantCulture,
                                    DateTimeStyles.AssumeUniversal);

From the docs of DateTimeStyles.AssumeUniversal:

If no time zone is specified in the parsed string, the string is assumed to denote a UTC.

Sounds like exactly what you want :)

(Alternatively you could use Noda Time and parse it to a LocalDate. It only represents a date, after all, so why use a type which cares about times and time zones? :)

like image 145
Jon Skeet Avatar answered Dec 07 '25 23:12

Jon Skeet



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!