Home > Back-end >  How to parse datetime returns from ToString
How to parse datetime returns from ToString

Time:04-29

When I use the following datetime format in the Windows calendar settings.

Short date: M/d
Long time: H:mm:ss

The following code can't work.

var s = DateTime.Now.ToString(); // 4/28 8:00:00
var b = DateTime.TryParse(s, out dt); // false

The string is returned from a library, so I cannot change it, is it possible to write a parsing method that works for any kind of datetime format in the Windows calendar settings?


Update, from @MathiasR.Jessen's suggestion, I have found a solution, but it is not elegant because I have to concatenate the format string manually.

var dtf = CultureInfo.CurrentCulture.DateTimeFormat;
var fmt = dtf.ShortDatePattern   " "   dtf.LongTimePattern;
var b = DateTime.TryParseExact(s, fmt, null, DateTimeStyles.None, out dt);

Now the question changes to is there a better way?

CodePudding user response:

Note that DateTime.TryParse() or DateTime.Parse() will not understand just any custom format. For custom datetime formats you need to use DateTime.TryParseExact() and DateTime.ParseExact():

Here is a demo Demo with that would be able to parse your input string.

CodePudding user response:

You can Use "DatetTime.Now.ToString("yyyy-MM-dd")" it returns the value in year-shortMonth-date. You can change the format according to your code.

  •  Tags:  
  • c#
  • Related