How to parse a string with GMT into datetime in c#

176 Views Asked by At

I have this inputDateString: 15/03/2023 15:13:37 GMT and I want to convert it to datetime.

I am doing this: DateTime outputDate = DateTime.ParseExact(inputDateString, "MM/dd/yyyy:hhmmss \"GMT\"", CultureInfo.InvariantCulture);

I get this error: c# String '10/05/2023 18:19:27 GMT' was not recognized as a valid DateTime.

How can I convert this date string to a datetime?

2

There are 2 best solutions below

4
abolfazl  sadeghi On BEST ANSWER

your format date incorrect ,This code is correct,better but you must specify the timezone

DateTime outputDate = DateTime.ParseExact("15/03/2023 15:13:37 GMT", "dd/MM/yyyy HH:mm:ss GMT", CultureInfo.InvariantCulture);
0
ldvtlucas On
var date = DateTime.ParseExact("15/03/2023 15:13:37 GMT", "dd/MM/yyyy HH:mm:ss GMT", CultureInfo.InvariantCulture);

Should do the trick to parse from string to DateTime. If you want to mess with the timezones I recommend you to read about the DateTimeOffset class.

Having a DateTime class allows you to parse it to string the way you need passing the format you want:

Console.WriteLine( date.ToString("yyyy-MM-dd HH:mm:ss"));