1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

指定したタイムゾーンの時刻に変換する

Posted at

経緯

開発中はDateTime.Nowで東京時間が取得できるけど、デプロイするとロンドン時間が取れてしまうことがある。
最初はDateTime.Now.AddHours(9)とかしていたけど、きちんとした別の方法があったことが分かったので、備忘録として。

環境

言語:C#
バージョン:.NET Framework 4.8

コード

以下のように書くと、東京の現在時刻が取得できます。

TimeZoneInfo tokyoTimeZoneInfo = TimeZoneInfo.FindSystemTimeZoneById("Tokyo Standard Time");
DateTime dateTimeInTokyo = TimeZoneInfo.ConvertTime(DateTime.Now, tokyoTimeZoneInfo);

もちろん、タイムゾーンのIDを変えれば別の場所の時刻にも変換可能です。

拡張メソッドを用意する方法も紹介

最近、拡張メソッドというものを知ったので、そちらを使って任意の日時データを東京時間に変換するメソッドを作る方法も紹介します。

今回はExtensionsというフォルダにDateTimeExtensions.csファイルを作り、東京時間に変換する拡張メソッドを用意します。

Extensions/DateTimeExtensions.cs
public static class DateTimeExtensions
{
  public static DateTime ToTokyoTime(this DateTime dateTime)
  {
    TimeZoneInfo tokyoTimeZoneInfo = TimeZoneInfo.FindSystemTimeZoneById("Tokyo Standard Time");
    DateTime dateTimeInTokyo = TimeZoneInfo.ConvertTime(dateTime, tokyoTimeZoneInfo);
    return dateTimeInTokyo;
  }
}

後はExtensionsをusingに追加し、以下のように呼び出せば東京時間への変換が可能です。

DateTime.UtcNow.ToTokyoTime();

拡張メソッド便利ですね。

その他

この記事書き終えた後に見つけたのですが、大変参考になるのでおいておきます。

参考

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?