Convert a string (diffrent formats) to date

Hi

I got diffrent date formats from a database and I would like to convert the to a date. I don't have the option to work with the sql, since that query is fixed (long story)

"20051231","2005-12-31","2005-12-31 09:29:52" ==> "2005/12/31".

My first tought was to trim the string and remove "/" and " ", after that only read the first 6 char of the string and as the final step chope the string up in "2005","12","31". There after build upp "2005/12/31".

It seems to by much work and not so easy either as I tought.

Does anyone have any advice in thos matter.

/Matt



Answer this question

Convert a string (diffrent formats) to date

  • yza suklan

    To add to what has been said, you can use Parse or TryParse for the latter two of your examples. For the former you will either have to do some formatting to the string.

    I would recommend implementing a customer formatter (implementing IFormatProvider) which you can pass with the call to Parse or TryParse. This class would contain the logic instead of dirtying your existing class.



  • Jason Li

    Use the Convert class to convert a string to DateTime, then provide Invariant culture information as the secont parameter:



    DateTime dt = Convert.ToDateTime(
        "2005-12-31 09:29:52", 
        System.Globalization.DateTimeFormatInfo.InvariantInfo);
    MessageBox.Show(dt.ToString());

     


    Hope this helps,

    -chris



  • PoulErik

    hi, i analyze your problem. you can use

    try

    {

    string myDateTimeValue = "2005-12-31 09:29:52";// "2/16/1992 12:15:12";

    DateTime myDateTime = DateTime.Parse(myDateTimeValue);

    }

    catch

    {

    //for first case apply parse logic here for the string and make the string like

    //"2005-12-31"

    DateTime myDateTime = DateTime.Parse(myParsedValue);

    }

    20051231","2005-12-31","2005-12-31 09:29:52"

    try works fine for the second and third cases , but for the first case "20051231", its throwing exception so you parse this string and put "-" make the string compatibe for date format, in the catch block


  • Convert a string (diffrent formats) to date