In the code below,keyValuePair[0] is a string representation of an hour 0-23,ie keyValuePair[0] == "2"
to represent 2:00 AM. 13 for 1:00PM. I want to be able displaying this value in both 12 and 24 hour clocks.
an example:
keyValuePair[0] == 13
makes the value time
equal "13:00" OR 1:00 PM" depending on the current Culture.
time = DateTime.ParseExact(keyValuePair[0], "H", CultureInfo.CurrentCulture).ToString("t");
This works only when keyValuePair[0] has a 2 digit value,and I switch the format "H"
to "HH"
.However, my input can possibly be 1 digit input.When the input is 1 digit long and I use the format "HH"
I get an invalid format exception.
Perhaps there is a simpler way to do this? I guess I should just use "HH" and add a zero to keyValuePair[0]?
time = new DateTime(1, 1, 1, Convert.ToInt32(keyValuePair[0]), 0, 0).ToString("t");
"H" doesn't work because a single-character format string is assumed to be a standard date and time format string , but "H" is not one of the standard formats. To specify a custom format string with a single specifier , prefix the specifier with "%":
time = DateTime.ParseExact(keyValuePair[0], "%H", CultureInfo.CurrentCulture).ToString("t");
Note: Both DateTime.ParseExact
and new DateTime(1, 1, 1, h, 0, 0)
(Nimesh's answer) will validate that the specified hour is between 0 and 23. In contrast, DateTime.AddHours(h)
and new TimeSpan(h, 0, 0)
will accept values of h
less than 0 or greater than 23.
只需使用PadLeft(2, '0')
实现您想要的!
time = DateTime.ParseExact(keyValuePair[0].PadLeft(2, '0'), "HH", CultureInfo.CurrentCulture).ToString("t");
int input = int.Parse(keyValuePair[0]);
time = DateTime.Today.AddHours(input).ToString("t");
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.