我正在閱讀這樣的外部 API 日期:
2022-05-13 07:05:00
2022-05-13 13:00:00 ...
這些日期以 CET 時間固定。我想將它們轉換為 UTC 格式,例如“yyyy-MM-ddTHH:mm:sszzz”,這樣我就可以看到 UTC 偏移量 02:00。
問題是我沒有找到如何指定我的日期在 CET 時區的方法。ConvertTime、ConvertTimeToUtc 等函式不起作用。
我的代碼是:
var time = new DateTime(2022,5,26,8,15,00, DateTimeKind.Unspecified); // 2022-05-26 8:15:00 CET
TimeZoneInfo tz = TimeZoneInfo.FindSystemTimeZoneById("Central European Standard Time");
DateTime cet = TimeZoneInfo.ConvertTime(time, tz); // non sense, as no timezone info in time...
var str = cet.ToString("yyyy-MM-ddTHH:mm:sszzz");
如何解決這個問題?
uj5u.com熱心網友回復:
有一種更清潔的方法:
public static DateTime ParseCET(string dt)
{
var cet = TimeZoneInfo.FindSystemTimeZoneById("Central European Standard Time");
var localTime = DateTime.Parse(dt);
return TimeZoneInfo.ConvertTimeToUtc(localTime, cet);
}
輸出一致且正確,始終遵守夏令時:
// winter time - prints "2/1/2022 11:00:00 AM"
Console.WriteLine(ParseCET("2022-02-01 12:00:00").ToString());
// summer time - prints "8/1/2022 10:00:00 AM"
Console.WriteLine(ParseCET("2022-08-01 12:00:00").ToString());
邊緣情況:
- 當夏令時從冬季變為夏季時,時鐘從02:00:00跳到03:00:01,因此沒有類似
2022-03-27 02:30:00 CET.
在這種情況下,根據檔案并拋出例外:
如果 dateTime 對應于無效時間,則此方法將引發 ArgumentException。
- 當夏令時從夏季時間更改為冬季時間時,時鐘會從03:00:00跳轉到02:00:01,因此例如
2022-10-30 02:30:00 CET可以在邏輯上轉換為00:30:00 UTC 或01:30:00 UTC。
在這種情況下,根據檔案標準(冬季)時間假設:
如果 dateTime 對應的時間不明確,則此方法假定它是源時區的標準時間。
uj5u.com熱心網友回復:
您可以使用以下方法手動設定小時數:
// Currently CET is ahead of UTC by 2 hours
time = time.AddHours(-2);
然后您可以格式化日期時間物件而無需擔心時區。
編輯:添加夏令時。
首先,您必須檢查您是否處于夏令時生效的時間。
為此,首先獲取日期時間,然后檢查它是否處于夏令時。夏令時于 3 月的最后一個星期日生效,并于 10 月的最后一個星期日取消
currentTime = DateTime.Now();
string currentMonth = currentTime.ToString("MM");
string currentDay = currentTime.ToString("DD");
// Daylight saving is in effect
if ( currentMonth > '3' && currentMonth < '10' ) {
time = time.AddHours(-2);
}
// Daylight saving is not in effect
else if ( currentMonth < '3' || currentMonth > '10' ) {
time = time.AddHours(-1);
}
// If it is march or october
else if(currentMonth == '3' || currentMonth == '10')
{
// Find the last sunday
var lastSunday = new DateTime(currentTime.Year,currentTime.Month,1);
lastSunday = lastSunday.AddMonths(1).AddDays(-1);
while (lastSunday.DayOfWeek != DayOfWeek.Sunday)
{
lastSunday = lastSunday.AddDays(-1);
}
string sunday = lastSunday.ToString("DD");
// If it is march, check to see if the day is after or before last sunday
if(currentMonth == '3'){
if( currentDay > sunday )
{
// Daylight saving is in effect
time = time.AddHours(-2);
}
else
{
// It is not in effect
time = time.AddHours(-1);
}
}
// If it is october, check to see if the day is after last sunday or not
else if(currentMonth == '10'){
if( currentDay > sunday )
{
// Daylight saving is not in effect
time = time.AddHours(-1);
}
else
{
// It is in effect
time = time.AddHours(-2);
}
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/483926.html
上一篇:如果多列中的值與另一個資料框匹配,則根據pandas的日期范圍獲取總和
下一篇:在特定時間范圍內啟動函式
