Convert numbers to time?

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

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

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

See documentation for format codes.

Method 2

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));

Method 3

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


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x