Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find the correct custom format for a date-time string

I read date-time strings from a file in 2 different formats:

  1. 19/02/2019 08:24:59
  2. 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.

like image 987
user2102327 Avatar asked Mar 04 '23 10:03

user2102327


1 Answers

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";
like image 137
Dmitry Bychenko Avatar answered Mar 23 '23 03:03

Dmitry Bychenko