Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I parse a datetime string containing GMT in the end as its timezone? [duplicate]

Tags:

c#

.net

datetime

I have a datetime in the following format: Wed, 03 September 2013 02:05:50 GMT

Now when i try to parse this string to a datetime object using a mask, i get a formatexception

DateTime parsed = DateTime.ParseExact("Wed, 03 September 2013 02:05:50 GMT", "ddd, dd MMMM yyyy HH:mm:ss zzz", CultureInfo.InvariantCulture);

I did check DateTime.Now with the above mask, and it matches the date i want to parse exactly. How can i parse this date?

like image 701
Richard Mosselveld Avatar asked Oct 25 '13 09:10

Richard Mosselveld


People also ask

What is parsing how to parse a date time string?

The Parse method tries to convert the string representation of a date and time value to its DateTime equivalent. It tries to parse the input string completely without throwing a FormatException exception.

How do I convert a string to a datetime in Python?

We can convert a string to datetime using strptime() function. This function is available in datetime and time modules to parse a string to datetime and time objects respectively.

How to use DateTime ParseExact in c#?

ParseExact(String, String, IFormatProvider) Converts the specified string representation of a date and time to its DateTime equivalent using the specified format and culture-specific format information. The format of the string representation must match the specified format exactly.

What does DateTime parse return?

parse() The Date. parse() method parses a string representation of a date, and returns the number of milliseconds since January 1, 1970, 00:00:00 UTC or NaN if the string is unrecognized or, in some cases, contains illegal date values (e.g. 2015-02-31).


2 Answers

Try this:

DateTime parsed = DateTime.ParseExact("Tue, 03 September 2013 02:05:50 GMT", 
                                      "ddd, dd MMMM yyyy HH:mm:ss Z", 
                                       CultureInfo.InvariantCulture);

You should use Z for utc as "GMT". And the 3th of September was on a Tuesday.

like image 174
Stefan Avatar answered Oct 22 '22 22:10

Stefan


You may try:

var input = "Tue, 03 September 2013 02:05:50 GMT";
var parsed = DateTime.ParseExact(input,
    "ddd, dd MMMM yyyy HH':'mm':'ss 'GMT'",
    CultureInfo.InvariantCulture);
Console.WriteLine(parsed);
Console.WriteLine(parsed.ToLocalTime());
like image 30
Alex Filipovici Avatar answered Oct 22 '22 22:10

Alex Filipovici