简体   繁体   中英

String not converting to datetime

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 am"

So how to convert this to datetime in c#?

There is no built-in functionality for your "am or pm", 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);

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 "am" or "pm" 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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM