TL:DR:我有以下的輸入字符串:解析日期和轉換西歐標準時間爲UTC
Thu Mar 09 2017 18:00:00 GMT+0100
,我試圖使用的格式將其轉換爲一個DateTime
對象:
"ddd MMM dd yyyy HH:mm:ss"
這顯然不起作用,因爲我忽略了GMT+0100
部分。我怎樣才能包括這個?
我不設法解析和下面的輸入轉換爲正確的UTC DateTime對象:
輸入字符串selectedDate:
1,Thu Mar 09 2017 18:00:00 GMT+0100 (W. Europe Standard Time)
功能:
var splittedValues = selectedDate.Split(',');
var selectDayOfWeek = (DayOfWeek)int.Parse(splittedValues[0]);
var selectedTime = DateTime.ParseExact(splittedValues[1].Substring(0, 24),
"ddd MMM d yyyy HH:mm:ss",
CultureInfo.InvariantCulture);
DateTime today = new DateTime(DateTime.Today.Ticks, DateTimeKind.Unspecified);
// The (... + 7) % 7 ensures we end up with a value in the range [0, 6]
int daysUntilNextTargetDay = ((int)selectDayOfWeek - (int)today.DayOfWeek + 7) % 7;
DateTime nextTargetDay = today.AddDays(daysUntilNextTargetDay).AddHours(selectedTime.Hour).AddMinutes(selectedTime.Minute);
return nextTargetDay.ToUniversalTime();
結果時間部分總是18:00:00
應該是17:00
作爲輸入實際上是格林威治標準時間+01
這是什麼問題?
更新: 爲別人指出有錯誤,所以我我的代碼更新爲:
var splittedValues = selectedDate.Split(',');
var selectDayOfWeek = (DayOfWeek)int.Parse(splittedValues[0]);
var selectedTime = DateTime.ParseExact(splittedValues[1].Substring(0, 33),
"ddd MMM dd yyyy HH:mm:ss",
CultureInfo.InvariantCulture).ToUniversalTime();
// The (... + 7) % 7 ensures we end up with a value in the range [0, 6]
int daysUntilNextTargetDay = ((int)selectDayOfWeek - (int)DateTime.Today.DayOfWeek + 7) % 7;
DateTime nextTargetDay = DateTime.Today.AddDays(daysUntilNextTargetDay).AddHours(selectedTime.Hour).AddMinutes(selectedTime.Minute);
return nextTargetDay;
但現在的解析爲字符串不匹配失敗"ddd MMM dd yyyy HH:mm:ss"
如何在GMT + 0100必須是包括在這裏?
爲什麼你把它標記爲JavaScript? – mason
首先選擇一種語言C#或JavaScript。其次我認爲'd'應該是'dd',但我可能是錯的。第三,你的子串長度爲24個字符,有效地返回'Thu Mar 09 2017 18:00:00',所以'DateTime'對象無法知道它應該加1. – TheLethalCoder
結果是'18:00:00'你的意思是'selectedTime'擁有那個值? – TheLethalCoder