Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# : How to convert string to DateTime, where the string can have any of the standard datetime format

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

like image 700
InfantPro'Aravind' Avatar asked Dec 11 '09 07:12

InfantPro'Aravind'


People also ask

What C is used for?

C programming language is a machine-independent programming language that is mainly used to create many types of applications and operating systems such as Windows, and other complicated programs such as the Oracle database, Git, Python interpreter, and games and is considered a programming foundation in the process of ...

Is C language easy?

C is a general-purpose language that most programmers learn before moving on to more complex languages. From Unix and Windows to Tic Tac Toe and Photoshop, several of the most commonly used applications today have been built on C. It is easy to learn because: A simple syntax with only 32 keywords.

What is C in C language?

What is C? C is a general-purpose programming language created by Dennis Ritchie at the Bell Laboratories in 1972. It is a very popular language, despite being old. C is strongly associated with UNIX, as it was developed to write the UNIX operating system.

What is the full name of C?

In the real sense it has no meaning or full form. It was developed by Dennis Ritchie and Ken Thompson at AT&T bell Lab. First, they used to call it as B language then later they made some improvement into it and renamed it as C and its superscript as C++ which was invented by Dr.


1 Answers

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.

like image 169
Fredrik Mörk Avatar answered Sep 20 '22 16:09

Fredrik Mörk