I read date-time strings from a file in 2 different formats:
19/02/2019 08:24:59
2/17/2019 12:25:46 PM
For the first format the custom format string I wrote is:
string firstDate = "19/02/2019 08:24:59";
string customFormatForFirstDateTimeString = "dd/mm/yyyy hh:mm:ss";
and I use it as follows:
string firstResultingDateAndTime;
bool parsingSuccessful = DateTime.TryParseExact(
firstDate,
customFormatForFirstDateTimeString,
System.Globalization.CultureInfo.InvariantCulture,
System.Globalization.DateTimeStyles.None,
out firstResultingDateAndTime);
The problem is that parsingSuccessful
results false
.
For the second date-time string, the code is as follows:
string secondDate = "2/17/2019 12:25:46 PM";
string customFormatForSecondDateTimeString = "m/dd/yyy hh:mm:ss PM";
string secondResultingDateAndTime;
parsingSuccessful = DateTime.TryParseExact(
secondDate,
customFormatForSecondDateTimeString,
System.Globalization.CultureInfo.InvariantCulture,
System.Globalization.DateTimeStyles.None,
out secondResultingDateAndTime);
Also here I receive
parsingSuccessful == false;
I reckon that the custom format strings do not fit the date-time strings, but I was not able to figure out why. Please help. Thank you in advance.
Well, mm
stands for minutes, not months (we have MM
for it) that's why dd/mm/yyyy
format should be dd/MM/yyyy
.
Another issue with hour format where we have hh
for 0..12
range (with tt
for AM/PM
) and HH
for 0..23
interval:
string firstDate = "19/02/2019 08:24:59";
// Since we don't have AM / PM we can conclude that hour is in 0..23 range
string customFormatForFirstDateTimeString = "dd/MM/yyyy HH:mm:ss";
string secondDate = "2/17/2019 12:25:46 PM";
string customFormatForSecondDateTimeString = "M/dd/yyyy hh:mm:ss tt";
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With