简体   繁体   中英

How to parse string into datetime format

I want to parse a date-time string into a DateTime data type.

The format of the string is like 08/10/2013 09:49 PM , and I want it to go to the form 2013-10-08 21:49:05.6500000

The following is my code but it's not working.

public static DateTime ConvertDateTime(String arg_dateTime)
{
    try
    {
        return DateTime.ParseExact(arg_dateTime, 
            "dd/MM/yyyy H:m:s fff", 
            System.Globalization.CultureInfo.InvariantCulture);
    }
    catch(Exception exp)
    {
        return DateTime.Now;
    }
}

Your format string doesn't match your input data. Try a format string of "dd/MM/yyyy HH:mm:ss tt" , and see the custom date and time format documentation for more information.

Note that rather than catching an exception if it fails, you should use DateTime.TryParseExact and check the return value. Or if a failure here represents a big failure, just use ParseExact and don't catch the exception. Do you really want to default to DateTime.Now ? It seems unlikely to me. You should strongly consider just letting the exception propagate up.

Also, your method doesn't return a particular format - it returns a DateTime . That doesn't know anything about a format - if you want to convert the value to a specific format, you should do so specifically.

Is that you need to use ParseExact only?

Why not Parse ?

string arg_dateTime = "2013-10-08 21:49:05.6500000";
var dt =  DateTime.Parse(arg_dateTime, System.Globalization.CultureInfo.InvariantCulture);
Console.WriteLine(dt);//this works

Here is the Demo

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