Time-to-time sync for specific C # format

There is a line 2020-12-27 20:00:00

. The application must parse it into a DateTime structure. Expected format yyyy-MM-dd hh:mm:ss

. I use:

DateTime.TryParseExact(timeString, "yyyy-MM-dd hh:mm:ss", 
                       CultureInfo.InvariantCulture, DateTimeStyles.None, out time)

      

but that won't work. TryParseExact returns false. Does anyone know why?

+3


source to share


3 answers


hh

- 12 hour format, you must use hh

within 24 hours

So your example:



DateTime.TryParseExact(timeString, "yyyy-MM-dd HH:mm:ss", 
                       CultureInfo.InvariantCulture, DateTimeStyles.None, out time)

      

+6


source


You need to use HH

specifier instead HH

.

HH

specifier
for 24-hour clock format ( 00

to 23

), but HH

specifier
for 12-hour clock format ( 01

to 12

).



string s = "2020-12-27 20:00:00";
DateTime dt;
if(DateTime.TryParseExact(s, "yyyy-MM-dd HH:mm:ss", CultureInfo.InvariantCulture,
                          DateTimeStyles.None, out dt))
{
    // 27.12.2020 20:00:00
}

      

+8


source


You can use the method I wrote to convert DT from any format string:

public static DateTime? parseDate(this string date, string format = @"ddMMyyyy")
{                    
    format += "HHmmss";
    DateTime dt;            
    try 
    {
        string day = date.Substring(format.IndexOf('d'), 2);
        string month = date.Substring(format.IndexOf('M'), 2);
        string year = date.Substring(format.IndexOf('y'), 4);               
        string hour = date.Length - 1 > format.IndexOf('H')? date.Substring(format.IndexOf('H'), 2) : "00";
        string minute = date.Length - 1 > format.IndexOf('m')? date.Substring(format.IndexOf('m'), 2) : "00";
        string second = date.Length - 1 > format.IndexOf('s')? date.Substring(format.IndexOf('s'), 2) : "00";

        dt = DateTime.Parse(year + "/" + month + "/" + day + " " + hour + ":" + minute + ":" + second);
    }
    catch { return null; }
    return dt;
}

      

Using:

string date = "2014ASDA04QWER05zxc";
DateTime? dt = date.parseDate("yyyyxxxxMMxxxxdd");

      

Result: 2014/04/05 00:00

However, you are correct, perhaps you should use DateTime.ParseExact

HH instead hh

, as my method is too complicated for that.

A small comparison of the two methods using 20,000 random dates: enter image description here

0


source







All Articles