简体   繁体   中英

Cannot Parse date time format

I cannot seem to parse a date-time such as,

"7/10/2019 2:52:52 PM".

No matter which format I add It won't work. Here's my code:

public static DateTime? ToInternal(string source)
{
    if (!DateTime.TryParseExact(
           source,
           PUBLIC_INPUT_FORMAT_STRING,
           System.Globalization.CultureInfo.InvariantCulture,
           System.Globalization.DateTimeStyles.None,
           out DateTime date))
    {
        return null;
    }
    else
    {
        return date;
    }
}

public static string[] PUBLIC_INPUT_FORMAT_STRING =
{
    "yyyy-MM-dd", "dd/M/yyyy", "d/M/yyyy", "d/MM/yyyy",
    "dd/MM/yy", "dd/M/yy", "d/M/yy", "d/MM/yy","yyyy/MM/dd",
    "yyyy-MM-dd HH:mm tt","yyyy'-'MM'-'dd'T'HH':'mm':'ss", 
    "dd/M/yyyy HH:mm:ss tt", "d/MM/yyyy H:mm:ss tt",
    "d/M/yyyy HH:mm:ss", "d/MM/yyyy HH:mm:ss","dd/MM/yyyy HH:mm:ss"
};

You should mention PM as tt and use h (not H ) since hour is in 12-hour format , ie

string source = "7/10/2019 2:52:52 PM";

DateTime result = DateTime.ParseExact(
   source, 
  "M/d/yyyy h:m:s tt",  // if "7/10/2019" means "10 July 2019"
   CultureInfo.InvariantCulture);

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