AM and PM with "Convert.ToDateTime(string)"

Hi there,

I have a string which holds a date and a time:
string s = 18.11.2005 11:23:03 PM

When converting it to a DateTime by:
Convert.ToDateTime(s);
I get:
18.11.2005 11:23:03

But now, I'm not able to tell the difference between day an night.
I need the AM and PM. How can I keep/get it

Thank you,

Finch.


Answer this question

AM and PM with "Convert.ToDateTime(string)"

  • Jawad Naeem

    A DateTime structure does not store it's value in any string format, instead it uses its own internal representation.

    You can use DateTiime.ToString() to control how the date time is converted as a string.

    For more information, have a look up 'Standard date and time format strings' in the Visual Studio index.

    If you have Visual Studio 2005 installed, you can use the following link:

    Standard DateTime Format Strings



  • Jakob Rojel

    Your code works fine for changing that string into a DateTime object... What you need to do is to get it to output to a AM/PM format... 

    Try this (the simplest way to do it):


    (DateTime).ToString("dd.MM.yyyy hh:mm:ss tt");
     



  • IanSJ

    If you want to sort dates represented as strings, you may choose appropriate string format like that:
    DateTime.Now.ToString("s");
    Format "s" was specially provided for sorting dates as strings... I guess :)

    Also you may sort the items in your comboBox manually.

  • mezza_pete

    NOTE:
    The point is that my locale is russian and your code will not work good.
    In russian culture Manip's code outputs "18.11.2005 11:23:03 " without AM\PM designator but hour value will changed correctly (11 instead of 23).

  • MA

    string s = "18.11.2005 11:23:03 PM";
    DateTimeFormatInfo fi = new CultureInfo( "en-US", false ).DateTimeFormat;
    DateTime myDate = DateTime.ParseExact(s, "dd.MM.yyyy hh:mm:ss tt", fi);
    Console.WriteLine("original string:\t{0}", s);
    Console.WriteLine("Parsed value:\t{0}", myDate.ToString("dd.MM.yyyy hh:mm:ss tt", fi));

  • buckabucka

    Your guys' code works "actually" fine. I get the "time" with AM/PM but:

    When printing the converted dates to a comboBox and sorting them, the dates get sorted as strings (31.April > 01.Dez because 3 > 0).


    Finch.

  • AM and PM with "Convert.ToDateTime(string)"