簡體   English   中英

DateTime.ParseExact引發格式“ H”的格式異常

[英]DateTime.ParseExact throwing format exception for format “H”

在下面的代碼中,keyValuePair [0]是0-23小時的字符串表示形式,即keyValuePair[0] == "2"表示2:00 AM。 13表示下午1:00。 我希望能夠在12和24小時制中顯示此值。

一個例子:

keyValuePair[0] == 13使值time等於“ 13:00”或“ 1:00 PM”,具體取決於當前的區域性。

time = DateTime.ParseExact(keyValuePair[0], "H", CultureInfo.CurrentCulture).ToString("t");

僅當keyValuePair [0]具有2位數字的值,並且我將格式"H"切換為"HH"但是,我的輸入可能是1位數字的輸入。當輸入為1位數字的長且使用格式時"HH"我收到無效的格式異常。

也許有一種更簡單的方法可以做到這一點? 我想我應該只使用“ HH”並向keyValuePair [0]添加零?

time = new DateTime(1, 1, 1, Convert.ToInt32(keyValuePair[0]), 0, 0).ToString("t");

“ H”不起作用,因為假定單個字符格式的字符串是標准的日期和時間格式字符串 ,但是“ H”不是標准的格式之一。 要使用單個說明符指定自定義格式字符串,請在說明符前面加上“%”:

time = DateTime.ParseExact(keyValuePair[0], "%H", CultureInfo.CurrentCulture).ToString("t");

注意: DateTime.ParseExactnew DateTime(1, 1, 1, h, 0, 0) 1、1、1 new DateTime(1, 1, 1, h, 0, 0) (Nimesh的答案)都將驗證指定的小時在0到23之間。相反, DateTime.AddHours(h)new TimeSpan(h, 0, 0)將接受小於0或大於23的h值。

只需使用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");

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM