1

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?

3
  • While you probably still need to adjust your format, I'd recommend parsing to DateTimeOffset rather than DateTime. Commented May 13, 2023 at 1:20
  • What timezone is your current computer in? Will you always get input strings that end with "GMT"? Commented May 13, 2023 at 1:27
  • Yes, I will always get input strings that end with "GMT". Commented May 13, 2023 at 1:29

2 Answers 2

2

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);
Sign up to request clarification or add additional context in comments.

4 Comments

Is there a way to format the output while still keeping it a date? For example right now the output is in this format: Feb 28 2023 6:29AM, but I want it to be in this format: 2023-05-13 01:40:34
If this is what you mean, when we convert it to a string, it should be in that format. You can use this code "outputDate.ToString("yyyy-MM-dd HH:mm:ss")"
I am saving to a sql table date field. I want the value I send to sql to be a date formatted as 2023-05-13 01:40:34, not a string.
If you send a date to the database, it will be sent as a date and it will be known there and can use format
0
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"));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.