locked
Convert string to date RRS feed

  • Question

  • Hi,

    I have string in unknown format of the date. I need to convert it to DateTime. How can I do this?

    Thank's
    Alexei

    Tuesday, March 21, 2006 1:16 PM

Answers

  • You can specify the format in the Parse method of the DateTime struct.


    string stringA = "1-1-2000";
    DateTimeFormatInfo formatA = new DateTimeFormatInfo();
    // TODO: Set the format's for formatA.

    string stringB = "01/01/2000";
    DateTimeFormatInfo formatB = new DateTimeFormatInfo();
    // TODO: Set the format's for formatB.

    DateTime dateA = DateTime.Parse( stringA, formatA );
    DateTime dateB = DateTime.Parse( stringB, formatB );

    if( dateA < dateB )
    {
        // Date A is smaller.
    }

     

    Tuesday, March 21, 2006 2:27 PM
  • Just look at my example, you can use the DateTimeFormatInfo class to specify the data format when parsing it.
    Wednesday, March 22, 2006 8:11 AM

All replies

  • Why do you have a unknown format, then you can never parse it to a DateTime object. Because you need to know what the month, date and year is.
    Tuesday, March 21, 2006 1:24 PM
  • Hi,

    After I convert the string to datetime I want to compare it to another value that is datetime too. But they isn't same format. So how can I change the format of date of converted value.

    Thank's
    Alexei

    Tuesday, March 21, 2006 2:20 PM
  • You can specify the format in the Parse method of the DateTime struct.


    string stringA = "1-1-2000";
    DateTimeFormatInfo formatA = new DateTimeFormatInfo();
    // TODO: Set the format's for formatA.

    string stringB = "01/01/2000";
    DateTimeFormatInfo formatB = new DateTimeFormatInfo();
    // TODO: Set the format's for formatB.

    DateTime dateA = DateTime.Parse( stringA, formatA );
    DateTime dateB = DateTime.Parse( stringB, formatB );

    if( dateA < dateB )
    {
        // Date A is smaller.
    }

     

    Tuesday, March 21, 2006 2:27 PM
  • Hi,

    Example of dates:
    One date is in format 23/01/2004. Second is 01/23/2004.
    When I convert both of them to datetime and compare them it tells me that it not same. But it is but it is not same date format.

    How can I solve it?

    Thank's
    Alexei

    Wednesday, March 22, 2006 7:26 AM
  • Just look at my example, you can use the DateTimeFormatInfo class to specify the data format when parsing it.
    Wednesday, March 22, 2006 8:11 AM
  • This "reply" is a good example of a lazy post because it gives incomplete example code because of the two "To Do" lines.  The documentation on converting strings to dates is poor, with lots of articles sending one round the houses. 

     

    The datetimeformat link that the reply refers to is about how to use formats to write dates to strings, not the other way round.   It may be that the same formats will work the other way round, but why not replace the 2 To Do lines with 2 lines (I suspect it may be no more than that) showing an example of how to set the formats?

     

    It is not at all clear how to do simple conversions such as from "06 04 1997" or "6 Apr 1997" to DateTime in .net 2 (which should produce 6 April 1997 with a en-GB culture), one gets uninformative error messages such as "Index was outside the bounds of the array" when using

    Convert.ToDateTime(string)

    or DateTime.Parse(string)

     

    So please stop being so complacent about an issue which is currently poorly documented in .net 2.

     

     

     

    Tuesday, August 21, 2007 10:00 AM
  • I think I now see what is going on with regard to the way strings are intended to be converted to dates in .net 2.  As mentioned above, the current documentation is very poor, in particular because it does not explain any of the reasoning behind why particular methods are provided, or how they should be used. (e.g. http://msdn2.microsoft.com/en-us/library/2h3syy57(VS.90).aspx should point out the dangers of using Parse and encourage the use of ParseExact or TryParseExact instead).  The documentation should also avoid recommending the Convert.ToDateTime method, because that seems to use Parse internally, i.e. Convert.ToDateTime("6 4 07") will not produce an error, but it should do because 6 4 07 could mean anything from 6 April 1907 to 4 June 2007!

     

    Thanks to posts from Boban and Matthew Watson I think the following is a sensible approach:

     

    Because string representations of dates and times can be very ambiguous (e.g. does 02/03/04 mean 2 March 2004 or 3 February 2004, or 1904?), it is not recommended to store dates as strings.  Instead, they should be entered via the DateTime picker which has a DateTime as Value property, or read in from a database which should store them as a DateTime.

     

    If dates have to be stored as strings (e.g. in a text file, or possibly a CSV file?), then it is not good practice (as used to be done in VB6 and is still done in VBA, e.g. if IsDate(mystring) then MyDate=DateValue(mystring)) to try and convert the string whatever format it may be in, because if any of the commonly used ambiguous date formats are used, such as 02/03/2004 the program effectively has to guess whether the format is dd/MM/yyyy (common in the UK) or MM/dd/yyyy (as most commonly used in the US) and can therefore make silent errors (the most dangerous kind because such errors are much less likely to be detected).  [Incidentally, M or MM should be used for months rather than m or mm, because m and mm are used for minutes in international standards].

     

    Since 1988, there has been an international standard for date time (ISO 8601) which is:

    YYYY-MM-DD for dates (4 digit year-2 digit month-2 digit day) and  

    hh:mmTongue Tieds for times (2 digit hour from 24 hour clock:2 digit minute:2 digit second)  (see http://www.cl.cam.ac.uk/~mgk25/iso-time.html or http://en.wikipedia.org/wiki/ISO_8601).

     

    One solution is to only accept (when converting strings to dates) strings which are in the ISO 8601 date format (YYYY-MM-DD) and to raise an error in all other cases.   This can be done with the .net 2 DateTime class's ParseExact method.  However, since our clients are almost all in English speaking countries, it seems sensible to also accept the dd MMM yyyy format (as in 02 Mar 2004) because this is more readily readable to most clients (and is also unambiguous whereas they are probably not yet familiar with the ISO 8601 format and may be unsure of the ordering of the days and month, since without letters the standard could have been defined as YYYY-DD-MM).

    So it seems sensible for us to accept strings in either YYYY-MM-DD (ISO 8601) or dd MMM yyyy (a very clear format for the English speaking world) formats.

     

    This can be achieved in C# (Visual Studio 2005) by:

      <code>

            DateTime ConvertStringToDate(String myString)

            {

                try

                {

                    return  DateTime.ParseExact(myString, "yyyy-MM-dd",   System.Globalization.CultureInfo.InvariantCulture); // this works with e.g. "1997-04-06"

                }

                catch

                {

                    // if we get here, the string was not in the ISO 8601 date format, so let's move on and try the other format

                }

                try

                {

                    return DateTime.ParseExact(myString, "dd MMM yyyy", new System.Globalization.CultureInfo("en-GB")); // this works with e.g. "06 Apr 1997"

                }

                catch (Exception e)

                {

                    // if we get here, the string was not in our alternative acceptable dd MMM yyyy format,

                    // so let's raise an error with enough information so that

                    // the user can identify which string is in the wrong format

                    // (too many Microsoft error messages currently just say something like

                    // "String was not recognized as a valid DateTime", this is silly because

                    // it doesn't help the user tell which string caused the error!

                    throw new Exception("Unable to convert the string " + myString +

                        " to a date.  To convert strings to dates unambiguously, accepted formats are YYYY-MM-DD (the ISO 8601 format, e.g. 1997-04-06) or dd MMM yyyy in English (e.g. 06 Apr 1997).   The system error message was:\n " + e.Message);

                }

            } // end TestConvertStringToDate

    </code>

    Friday, August 24, 2007 6:14 AM