views:

78

answers:

3

Is there a slick way to convert simple numbers (Army time included) to a time format (am, pm format)? I can do the tedious approach, but I was just wondering if there was another way

0800 => 8:00 am

2317 => 11:17 pm

+1  A: 

Hope this points you in the right direction:

    string time = "0800";
    DateTime dt = DateTime.ParseExact(string.Format("{0}:{1}", time.Substring(0, 2), time.Substring(2, 2)), "HH:mm", CultureInfo.InvariantCulture);
    MessageBox.Show(string.Format("{0:h:mm tt}", dt));

    time = "2345";
    dt = DateTime.ParseExact(string.Format("{0}:{1}", time.Substring(0, 2), time.Substring(2, 2)), "HH:mm", CultureInfo.InvariantCulture);
    MessageBox.Show(string.Format("{0:h:mm tt}", dt));
Robaticus
Why do you reformat the string to HH:mm format and not user directly HHmm format ?
Thibault Falise
Good question. Because I wrote it fast and didn't think about that. :)
Robaticus
+1  A: 

Use DateTime.TryParse with the format string you want.

If you can accept several formats then you'll need to call each in turn until you find the one that matches - which I assume is what you mean by "the tedious approach".

ChrisF
+9  A: 
    DateTime dt = DateTime.ParseExact("0800", "HHmm", CultureInfo.InvariantCulture);
    string timestring = dt.ToString("h:mm tt");

See documentation for format codes.

Brian