I had posted a question on DateTime to String conversion, I got many satisfying answers for that .. so I thank StackOverflow very much ..
Here is one more problem of String manupulation, I am stuck with ..
I have to convert a string (from some external source) using C# code .. the string can have these expected format of DateTime ..
02/31/2009 01:59:5924 hours format02/31/2009 01:59:59 AM12 hours format2/31/2009 1:59:592/31/2009 1:59:59 AM02/01/2009 01:59:59 AM2/1/2009 1:59:59- and so on …….
I tried using DateTime(Convert.ToInt32(string_date.Substring(6,4)),Int,Int,Int,Int,Int,Int)
ie, By extracting the values of month, Day etc
But it doesn’t work .. because I can’t extract the values with substring perfectly .. as the length of string is Varying
I also have tried to extract the values referring the occurance of “/”, “space” and “:” but it becomes bottle neck to derive with (non-)Occurrence of AM/PM
Only the length of Day, Month and Hours can vary ..
You can use the
DateTime.ParseExactoverload that takes a list of formats:This will throw a
FormatExceptionif the passed string does not match any of the given formats. Notice that the formats expecting AM/PM should appear before identical formats without AM/PM ("MM/dd/yyyy HH:mm:ss tt"comes before"MM/dd/yyyy HH:mm:ss").Update
As Henk points out in the comments, the same functionality is available when using
TryParseExactwhich removes exception situation. Also, paired with nullable types this can be made a bit cleaner:Now it will simply return a null reference if it fails to parse the input.