2017-07-27 76 views
0

日期時間分析錯誤發生在不在本地主機,可能是因爲本地主機和服務器上的時區不同, 代碼: 我想24小時時間格式爲12小時(AM和PM )字符串未被識別爲有效的DateTime。 :錯誤只在服務器

string timesx2 = hr2[0]+":" + hr2[1]; //  19:22 
string s2 = DateTime.ParseExact(timesx2, "HHmm", CultureInfo.CurrentCulture) 
    .ToString("hh:mm tt"); // output in localhost is: 7.22 PM 
+0

嘗試在c#中使用FindSystemTimeZoneById並轉換日期時間。 – summerGhost

+1

你用''HH:mm「'試過'ParseExact'嗎? –

+0

@MykolaKovalchuk是的,先生,我厭倦了HH:MM –

回答

0

您應該使用固定區域性(如果你不需要轉換到你的課程時區)

string timesx2 =hr2[0] + ":" + hr2[1]; //  19:22 
    string s2 = DateTime.ParseExact(timesx2, "HH:mm", CultureInfo.InvariantCulture).ToString("hh:mm tt", CultureInfo.InvariantCulture); // output in localhost is: 7.22 PM 

和it'l在印度文化確定。

+0

string s2 = DateTime.ParseExact(timesx2,「HH:mm」,null).ToString(「hh:mm tt」,CultureInfo。 InvariantCulture的);我也嘗試這一個 –

+0

相同的問題也會發生,而我轉換12小時至24小時**的DateTime StartTimein12 = Convert.ToDateTime(StartTimes [0] .StartTime [I]); string CovertedTime =(StartTimein12.ToString(「HH:mm」)); StartTimeDB = StartDates [0] .StartDate [I] + 「」 + CovertedTime; ** –

+0

你試圖前綴日期到串並解析它? 'string timesx2 =「2017-01-01」+ hr2 [0] +「:」+ hr2 [1]; // 19:22 string s2 = DateTime.ParseExact(timesx2,「yyyy-MM-dd HH:mm」,CultureInfo.CurrentCulture) .ToString(「hh:mm tt」); //在localhost中輸出的是:7.22 PM' –

0

您解析字符串缺少一個冒號。

當您嘗試解析由HHmm組成的字符串時,您組成的時間字符串格式爲HH:mm。這是行不通的。

如果您希望發生單位數小時,還要從輸出格式字符串中刪除第二個h。否則,輸出將是07:22 PM。

string timesx2 = hr2[0]+":" + hr2[1]; //  19:22 
string s2 = DateTime.ParseExact(timesx2, "HH:mm", CultureInfo.InvariantCulture) 
    .ToString("h:mm tt"); // output in localhost is: 7:22 PM 
+0

我兩種方式嘗試仍然不能 –

+0

你確認你的數組包含正確格式的值?例如數組中的值確實有2個數字字符,並且它們分別在小時和分鐘的時間範圍內?因爲這個代碼在我運行的時候可以工作。 – Adwaenyth

0

大寫「H」表示24小時的時間和小寫的「h」表示 12小時時間,尊重在候選字符串中的AM/PM。

DateTime.ParseExact("3/21/2015 8:56:04 AM", "M/d/yyyy h:mm:ss tt", CultureInfo.InvariantCulture) 
0

將您的本地時間爲UTC時間

DateTime utcTime = TimeZoneInfo.ConvertTimeToUtc(localDatetime); //Convert sent datetime to UTC. 

獲得從區域名稱時區信息。獲取區域名稱here

TimeZoneInfo zoneInfo = TimeZoneInfo.FindSystemTimeZoneById(zoneName); 
DateTime finalDatetime = TimeZoneInfo.ConvertTime(utcTime, zoneInfo); 
相關問題