views:

1179

answers:

4

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 ..

  1. 02/31/2009 01:59:59           24 hours format
  2. 02/31/2009 01:59:59 AM     12 hours format
  3. 2/31/2009 1:59:59
  4. 2/31/2009 1:59:59 AM
  5. 02/01/2009 01:59:59 AM
  6. 2/1/2009 1:59:59
  7. 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 ..

+6  A: 

Take a look at the TryParseExact method. Here's an example with the first case:

DateTime date;
// I changed 02/31/2009 to 01/31/2009 because the first is not a valid date
if (DateTime.TryParseExact("01/31/2009 01:59:59", "MM/dd/yyyy HH:mm:ss", null, DateTimeStyles.None, out date))
{
    // string successfully parsed => do something with the date
}

You could then keep a list of different formats and try to parse the string with all of them until you succeed.

Darin Dimitrov
Is there any other EFFICIENT way .. ?I mean its painful to type THOSE MANY LINES as many Lines I have as options ..
infant programmer
A: 

DateTime dt1 = DateTime.ParseExact("2007/01/01 04:23:12", "yyyy/MM/dd hh:mm:ss", System.Globalization.CultureInfo.CurrentCulture);

DateTime dt = Convert.ToDateTime("2007/01/01 04:23:12", System.Globalization.CultureInfo.CurrentCulture);

System.Globalization.CultureInfo.CurrentCulture format param

Clover
it doesn't work .. but thanx for trying ..
infant programmer
+11  A: 

You can use the DateTime.ParseExact overload that takes a list of formats:

private static string[] formats = new string[]
    {
        "MM/dd/yyyy HH:mm:ss tt",
        "MM/dd/yyyy HH:mm:ss",
        "M/dd/yyyy H:mm:ss tt",
        "M/dd/yyyy H:mm:ss"        
    };

private static DateTime ParseDate(string input)
{
    return DateTime.ParseExact(input, formats, CultureInfo.InvariantCulture, DateTimeStyles.None);
}

This will throw a FormatException if 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 TryParseExact which removes exception situation. Also, paired with nullable types this can be made a bit cleaner:

private static DateTime? ParseDate(string input)
{
    DateTime result;
    if (DateTime.TryParseExact(input, formats, CultureInfo.InvariantCulture, DateTimeStyles.None, out result))
    {
        return result;
    }
    return null;
}

Now it will simply return a null reference if it fails to parse the input.

Fredrik Mörk
This overload also exists for TryParseExact, no reason to let it come to an exception.
Henk Holterman
@Henk: thanks. I expected that but didn't find it. I now realize that I was only looking at `TryParse`...
Fredrik Mörk
+1 Nice snippet!
KMan
@Fredrik "return null" shows error .. as it is not type "DateTime"
infant programmer
@Aravind: note that the method in the last example has the return type `DateTime?` (note the question mark); this means that it is a nullable type, where `null` is a valid value.
Fredrik Mörk
ohk .. fine .. got it ..
infant programmer
+1  A: 

Here are all the possible formats ..

  1. MM/dd/yyyy 08/22/2006
  2. dddd, dd MMMM yyyy Tuesday, 22 August 2006
  3. dddd, dd MMMM yyyy HH:mm Tuesday, 22 August 2006 06:30
  4. dddd, dd MMMM yyyy hh:mm tt Tuesday, 22 August 2006 06:30 AM
  5. dddd, dd MMMM yyyy H:mm Tuesday, 22 August 2006 6:30
  6. dddd, dd MMMM yyyy h:mm tt Tuesday, 22 August 2006 6:30 AM
  7. dddd, dd MMMM yyyy HH:mm:ss Tuesday, 22 August 2006 06:30:07
  8. MM/dd/yyyy HH:mm 08/22/2006 06:30
  9. MM/dd/yyyy hh:mm tt 08/22/2006 06:30 AM
  10. MM/dd/yyyy H:mm 08/22/2006 6:30
  11. MM/dd/yyyy HH:mm:ss 08/22/2006 06:30:07
  12. MMMM dd August 22
  13. yyyy'-'MM'-'dd'T'HH':'mm':'ss.fffffffK 2006-08-22T06:30:07.7199222-04:00
  14. ddd, dd MMM yyyy HH':'mm':'ss 'GMT' Tue, 22 Aug 2006 06:30:07 GMT
  15. yyyy'-'MM'-'dd'T'HH':'mm':'ss 2006-08-22T06:30:07
  16. HH:mm 06:30
  17. hh:mm tt 06:30 AM
  18. H:mm 6:30
  19. h:mm tt 6:30 AM
  20. HH:mm:ss 06:30:07
  21. yyyy'-'MM'-'dd HH':'mm':'ss'Z' 2006-08-22 06:30:07Z
  22. dddd, dd MMMM yyyy HH:mm:ss Tuesday, 22 August 2006 06:30:07
  23. yyyy MMMM 2006 August
infant programmer