-2

I am getting a datetime format from my server but it is not converting, throwing exception always

Datetime format is : "31/5/2022 11:00:00 a. m."

So how to convert this to datetime in c#?

SP Tutorials
  • 15
  • 2
  • 7
  • 3
    Does this answer your question? [How to convert a string containing AM/PM to DateTime?](https://stackoverflow.com/questions/28672191/how-to-convert-a-string-containing-am-pm-to-datetime) – Mykyta Halchenko Jun 02 '22 at 10:34
  • @MykytaHalchenko Well, not exactly ... it will not work with "a. m." "p. m." .... – Selvin Jun 02 '22 at 10:39
  • ... but with custom AM/PM designators in DateTimeFormatInfo it is possible ... – Selvin Jun 02 '22 at 10:49
  • Does this answer your question? [Converting a String to DateTime](https://stackoverflow.com/questions/919244/converting-a-string-to-datetime) – abhi Jun 02 '22 at 17:41

2 Answers2

2

There is no built-in functionality for your "a. m. or p. m.", but you can try doing something like this because it is really specific format you have("AM" or "PM" in the end are supported by .NET platform):

string testStr = "31/5/2022 11:00:00 a. m.".Replace("a. m.","AM").Replace("p. m.", "PM");
string formatToParse = "d/M/yyyy h:mm:ss tt";
var res = DateTime.ParseExact(testStr , formatToParse, CultureInfo.InvariantCulture);
Mykyta Halchenko
  • 720
  • 1
  • 3
  • 21
  • Yeah I agree that pre-processing these would be the right call. If every line always ends in "a. m." or "p. m." you could just do a substring to chop off the end and then concatenate "AM" or "PM". That would probably be faster and not really any harder to code than the replace. Probably doesn't make much of a difference unless you're processing a lot of these at once. – shelleybutterfly Jun 02 '22 at 19:21
1

Have you considered asking the DBA to change the format for the column in the database?

declare @date datetime = '05-31-2022 11:00:00'
select ...,FORMAT(@date,'MM/dd/yyyy hh:mm:ss tt')

Otherwise see How to parse "string" to "DateTime" with "a. m." or "p. m." format (not AM/PM)?

Example from the post above

var value = "31/5/2022 11:00:00 a. m.";
DateTimeFormatInfo formatInfo = new DateTimeFormatInfo() { AMDesignator = "a. m.", PMDesignator = "p. m." };
var dateTime = DateTime.ParseExact(value, "dd/M/yyyy hh:mm:ss tt", formatInfo);
Karen Payne
  • 4,341
  • 2
  • 14
  • 31