タスクはWP7/Silverlightのフレームワークの助けを借りてarchievedすることができないことを見た後、私はその小さなヘルパーを書きました
public static class DateTimeHelper
{
/// <summary>
/// Tries to parse the given datetime string that is not annotated with a timezone
/// information but known to be in the CET/CEST zone and returns a DateTime struct
/// in UTC (so it can be converted to the devices local time). If it could not be
/// parsed, result contains the current date/time in UTC.
/// </summary>
public static bool TryParseCetCest(string s, string format, IFormatProvider provider, DateTimeStyles style, out DateTime result)
{
// Parse datetime, knowing it is in CET/CEST timezone. Parse as universal as we fix it afterwards
if (!DateTime.TryParseExact(s, format, provider, style, out result))
{
result = DateTime.UtcNow;
return false;
}
result = DateTime.SpecifyKind(result, DateTimeKind.Utc);
// The boundaries of the daylight saving time period in CET and CEST (_not_ in UTC!)
// Both DateTime structs are of kind 'Utc', to be able to compare them with the parsing result
DateTime DstStart = LastSundayOf(result.Year, 3).AddHours(2);
DateTime DstEnd = LastSundayOf(result.Year, 10).AddHours(3);
// Are we inside the daylight saving time period?
if (DstStart.CompareTo(result) <= 0 && result.CompareTo(DstEnd) < 0)
result = result.AddHours(-2); // CEST = UTC+2h
else
result = result.AddHours(-1); // CET = UTC+1h
return true;
}
/// <summary>
/// Returns the last sunday of the given month and year in UTC
/// </summary>
private static DateTime LastSundayOf(int year, int month)
{
DateTime firstOfNextMonth = new DateTime(year, month + 1, 1, 0, 0, 0, DateTimeKind.Utc);
return firstOfNextMonth.AddDays(firstOfNextMonth.DayOfWeek == DayOfWeek.Sunday ? -7 :
(-1 * (int)firstOfNextMonth.DayOfWeek));
}
}
トリックは、(これはTryParseExact
日付がUTCであると仮定し、日付変換/ローカルに調整を戻すことができる)なしDateTimeStyles.AssumeUniversalフラグをそれを解析することでUTCとしてrespecifyingとジョブを行いそれを手動でアクチュエータに調整するUTC相当です。
hereというDST規則に従います。私は夏時間の開始/終了の直前/直後に4つの境界ケースすべてでそれをテストしました。これは再びテストの重要性を示しました。DstStart.CompareTo(result) < 0
の<
演算子を<=
に変更して正しい結果を出さなければなりませんでした。
私はここでホイールを再発明している気がしましたが、私はこの単純な仕事のために専用の図書館を使いたくありませんでした。素晴らしいプロジェクトであるノーダタイムを見ましたが、これは必要ではないと思います。
私はこの小さなヘルパーで少し時間を節約することができれば幸いです。これは意図的にすべてのタイムゾーン(Noda Timeのようなlibを使用する必要がある場合)ではなく、私の場合のように1つの固定された単一のタイムゾーンを持つこれらのケースに対してです。
[c#fx 3.5の特定のタイムゾーンでのDateTimeの作成](http://stackoverflow.com/questions/246498/creating-a-datetime-in-a-specific-time-zone-in) -c-fx-3-5) –
@Michael Haren:いいえ、それは重複していません。私はこの質問をする前に私はこれを見て、それは私の特定の問題に役立たなかった。 –
おそらく重複はありませんが、助けてくれると思いました –