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?
source to share
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
}
source to share
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:
source to share