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
DateTime dt = DateTime.ParseExact("0800", "HHmm", CultureInfo.InvariantCulture);
string timestring = dt.ToString("h:mm tt");
See documentation for format codes.
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));
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".
精彩评论