0

How to convert below DateTime into C# (mm/dd/yy hh:mm:ss)

Oct 27 2022 9:09:50:693PM

Error string was not in recognized format

Tried with below code:

var cultureInfo = new CultureInfo("en-US", true);
DateTime LastUpdateDate = DateTime.Parse("Oct 27 2022  9:09:50:693PM", cultureInfo, DateTimeStyles.NoCurrentDateDefault);
                     
Diado
  • 2,229
  • 3
  • 18
  • 21
Shakeer Hussain
  • 2,230
  • 7
  • 29
  • 52
  • 3
    Does this answer your question? [Parse a string containing date and time in a custom format](https://stackoverflow.com/questions/2560540/parse-a-string-containing-date-and-time-in-a-custom-format) – Diado Aug 28 '20 at 06:39
  • 3
    note that `mm/dd/yy hh:mm:ss` is not "C# DateTime", that would be a _string representation_ of an existing DateTime, in en-US locale. `DateTime`is an abstraction, that has no intrinsic string format, until you call `ToString` or similar on it. – Pac0 Aug 28 '20 at 06:46

1 Answers1

7

Use DateTime.ParseExact() with "MMM dd yyyy h:mm:ss:ffftt" format,

using System;
using System.Globalization; 
...   

var cultureInfo = new CultureInfo("en-US", true);
DateTime LastUpdateDate = DateTime.ParseExact("Oct 27 2022  9:09:50:693PM", "MMM dd yyyy  h:mm:ss:ffftt", cultureInfo);
Console.WriteLine(LastUpdateDate.ToString());

.Net Fiddle


Note: You have two spaces between year and time. No space between milliseconds and AM/PM designator. Please check your string date and time and update format(Spaces in DateTime format) accordingly


MSDN documentation for Custom date and time format strings

Prasad Telkikar
  • 15,207
  • 5
  • 21
  • 44