システムのローカル時刻をUTCへ変換する - C#
システムのローカル時刻をUTCに変換するコードを紹介します。
概要
ローカルのTimeZoneInfoを取得し、TimeZoneInfoクラスのConvertTimeToUtc()メソッドに変換元のTimeZoneInfoを与えて呼び出すことで、ローカルの時刻をUTCに変換できます。
プログラム例
コード
private void button4_Click(object sender, EventArgs e)
{
string[] Formats = { "HH:mm:ss", "HH:mm" };
DateTime input = System.DateTime.ParseExact(textBox1.Text, Formats,
System.Globalization.DateTimeFormatInfo.InvariantInfo,
System.Globalization.DateTimeStyles.NoCurrentDateDefault);
TimeZoneInfo tzi = TimeZoneInfo.Local;
DateTime local = TimeZoneInfo.ConvertTimeToUtc(input, tzi);
textBox2.Text = local.ToString("HH:mm");
}
解説
string[] Formats = { "HH:mm:ss","HH:mm" };
DateTime input = System.DateTime.ParseExact(textBox1.Text, Formats,
System.Globalization.DateTimeFormatInfo.InvariantInfo,
System.Globalization.DateTimeStyles.NoCurrentDateDefault);
TextBox1に入力された文字列をDateTimeに変換します。受け付けるパターンは "HH:mm:ss"と"HH:mm"の2種類です。
TimeZoneInfo tzi = TimeZoneInfo.Local;
システムのローカルのTimeZoneInfoを取得します。
DateTime local = TimeZoneInfo.ConvertTimeToUtc(input, tzi);
ローカル時間をUTCに変換します。
textBox2.Text = local.ToString("HH:mm");
textBox2にUTC時間を表示します。
著者
iPentecのメインプログラマー
C#, ASP.NET の開発がメイン、少し前まではDelphiを愛用