WPF / C#でのタイムゾーンの表示。夏時間オフセットを発見する

StackOverflow https://stackoverflow.com/questions/226356

  •  03-07-2019
  •  | 
  •  

質問

DateTimeオブジェクトを対応するTimeZoneに変換するのにシステムレジストリがどのように役立つかを理解できません。リバースエンジニアリングを試みた例はありますが、夏時間に応じてUTCtimeがオフセットされるという1つの重要な手順を実行できません。

.NET 3.5(神に感謝)を使用していますが、それでも私を困惑させます。

ありがとう

編集:追加情報:この質問は、WPFアプリケーション環境で使用するためのものでした。私が残したコードスニペットは、私が探していたものを正確に得るために、答えの例をさらに一歩進めました。

役に立ちましたか?

解決

これは、WPFアプリケーションで使用しているC#のコードスニペットです。これにより、指定したタイムゾーンIDの現在の時刻(夏時間に合わせて調整)が得られます。

// _timeZoneId is the String value found in the System Registry.
// You can look up the list of TimeZones on your system using this:
// ReadOnlyCollection<TimeZoneInfo> current = TimeZoneInfo.GetSystemTimeZones();
// As long as your _timeZoneId string is in the registry 
// the _now DateTime object will contain
// the current time (adjusted for Daylight Savings Time) for that Time Zone.
string _timeZoneId = "Pacific Standard Time";
DateTime startTime = DateTime.UtcNow;
TimeZoneInfo tst = TimeZoneInfo.FindSystemTimeZoneById(_timeZoneId);
_now = TimeZoneInfo.ConvertTime(startTime, TimeZoneInfo.Utc, tst);

これは、私が結んだコードスニペットです。助けてくれてありがとう。

他のヒント

DateTimeOffsetを使用してUTCオフセットを取得できるため、その情報のためにレジストリを掘り下げる必要はありません。

TimeZone.CurrentTimeZoneは追加のタイムゾーンデータを返し、TimeZoneInfo.Localはタイムゾーンに関するメタデータ(夏時間、さまざまな状態の名前などをサポートするかどうかなど)を保持します。

更新:これはあなたの質問に具体的に答えていると思います:

var tzi = TimeZoneInfo.FindSystemTimeZoneById("Pacific Standard Time");
var dto = new DateTimeOffset(2008, 10, 22, 13, 6, 0, tzi.BaseUtcOffset);
Console.WriteLine(dto);
Console.ReadLine();

このコードは、-8オフセットでDateTimeを作成します。デフォルトでインストールされるタイムゾーンは、 MSDNにリストされています

//C#.NET
    public static bool IsDaylightSavingTime()
    {
        return IsDaylightSavingTime(DateTime.Now);
    }
    public static bool IsDaylightSavingTime(DateTime timeToCheck)
    {
        bool isDST = false;
        System.Globalization.DaylightTime changes 
            = TimeZone.CurrentTimeZone.GetDaylightChanges(timeToCheck.Year);
        if (timeToCheck >= changes.Start && timeToCheck <= changes.End)
        {
            isDST = true;
        }
        return isDST;
    }


'' VB.NET
Const noDate As Date = #1/1/1950#
Public Shared Function IsDaylightSavingTime( _ 
 Optional ByVal timeToCheck As Date = noDate) As Boolean
    Dim isDST As Boolean = False
    If timeToCheck = noDate Then timeToCheck = Date.Now
    Dim changes As DaylightTime = TimeZone.CurrentTimeZone _
         .GetDaylightChanges(timeToCheck.Year)
    If timeToCheck >= changes.Start And timeToCheck <= changes.End Then
        isDST = True
    End If
    Return isDST
End Function
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top