固有カルチャの日付と時刻の形式指定

更新 : 2007 年 11 月

DateTime 構造体には、アプリケーションで DateTime 型に対するカルチャに依存した操作に使用できるメソッドが用意されています。アプリケーションでは、DateTimeFormatInfo クラスを使用して、カルチャに基づいて DateTime 型の書式を設定し、表示できます。たとえば、ShortDatePattern を使用すると、2001 年 2 月 1 日という日付は、英語 (U.S.) カルチャ "en-US" では 2/1/2001 と書式化され、英語 (英国) カルチャ "en-GB" では 01/02/2001 と書式化されます。

DateTimeFormatInfo オブジェクトは、固有カルチャまたはインバリアント カルチャに対して作成でき、ニュートラル カルチャに対しては作成できません。ニュートラル カルチャでは、正しい日付形式を表示するために必要な情報が不足しています。アプリケーションがニュートラル カルチャを使用して DateTimeFormatInfo オブジェクトを作成しようとすると、例外がスローされます。DateTime 書式指定の詳細と使用例については、「日付と時刻の書式指定文字列」を参照してください。

CurrentThread の現在のカルチャが英語 (U.S.) の "en-US" に設定され、次にドイツ語 (ドイツ) の "de-DE" に設定されたときに ShortDatePattern を使用して現在の日付を表示するコード例を次に示します。

Imports System
Imports System.Globalization
Imports System.Threading

Public Class FormatDate
   
   Public Shared Sub Main()
      Dim dt As DateTime = DateTime.Now
      ' Sets the CurrentCulture property to U.S. English.
      Thread.CurrentThread.CurrentCulture = New CultureInfo("en-US")
      ' Displays dt, formatted using the ShortDatePattern
      ' and the CurrentThread.CurrentCulture.
      Console.WriteLine(dt.ToString("d"))
      
      ' Creates a CultureInfo for German in Germany.
      Dim ci As New CultureInfo("de-DE")
      ' Displays dt, formatted using the ShortDatePattern
      ' and the CultureInfo.
      Console.WriteLine(dt.ToString("d", ci))
   End Sub
End Class
using System;
using System.Globalization;
using System.Threading;

public class FormatDate
{
   public static void Main()
   {
      DateTime dt = DateTime.Now;
      // Sets the CurrentCulture property to U.S. English.
      Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US");
      // Displays dt, formatted using the ShortDatePattern
      // and the CurrentThread.CurrentCulture.
      Console.WriteLine(dt.ToString("d"));
      
      // Creates a CultureInfo for German in Germany.
      CultureInfo ci = new CultureInfo("de-DE");
      // Displays dt, formatted using the ShortDatePattern
      // and the CultureInfo.
      Console.WriteLine(dt.ToString("d", ci));
   }
}

このコードを 2001 年 7 月 9 日に実行すると、出力は次のようになります。

7/9/2001
09.07.2001

タイム ゾーンの使用

DateTime 構造体は、計算処理や比較処理では常に現地のタイム ゾーンを使用します。この点を考慮する必要があるのは、アプリケーションで Parse() メソッドと ParseExact() メソッドを使用する場合です。これらのメソッドにより提供されるオーバーロードによって、日付と時刻の文字列表現を DateTime 型の表現に変換できます。アプリケーションでは固有カルチャに合わせて DateTime 型の書式を指定することもできます。これらのメソッドは、受け取った文字列にタイム ゾーンが指定されていない場合、タイム ゾーン調整を行わずに解析済みの日付と時刻を取得します。日付と時刻は、オペレーティング システムのタイム ゾーン設定に基づきます。アプリケーションでタイム ゾーン オフセットを指定すると、これらのメソッドは日付と時刻の文字列を解析し、世界協定時刻 (UTC: Coordinated Universal Time) に変換してから、ローカル システムの時刻に変換します (世界協定時刻は、以前、グリニッジ標準時刻 (GMT: Greenwich Mean Time) と呼ばれていたものです)。

アプリケーションでは、ToUniversalTime メソッドを使用してローカルの DateTime 型を UTC 時刻に変換する必要があります。アプリケーションで日付と時刻の文字列を解析し、それを UTC の DateTime 型に変換するには、Parse() メソッドまたは ParseExact() メソッドに DateTimeStyles 列挙体の AdjustToUniversal 値を指定します。

次のコード例は、現地時刻の DateTime 型を作成し、それを対応する UTC 時刻に変換します。どちらの DateTime 型も文字列へ変換され、コンソールへ出力されます。この 2 つの文字列には、ローカル タイム ゾーンと UTC との間の UTC オフセット分の差があります。これらの文字列を再び DateTime 型に戻すには、ParseExact() メソッドを使用します。utcdt に格納されているタイム ゾーン情報を取り込むためには、ParseExact メソッドのパラメータとして DateTimeStyles の AdjustToUniversal 値を指定する必要があります。さまざまなタイム ゾーンの UTC オフセットの詳細については、「GetUtcOffset」を参照してください。

Imports System
Imports System.Globalization
Imports System.Threading

Public Class TimeZoneSample
   Public Shared Sub Main()
      Dim en As New CultureInfo("en-US")
      Thread.CurrentThread.CurrentCulture = en

      ' Creates a DateTime for the local time.
      Dim dt As New DateTime(2001, 7, 13, 4, 0, 0)

      ' Converts the local DateTime to the UTC time.
      Dim utcdt As DateTime = dt.ToUniversalTime()

      ' Defines a custom string format to display the DateTime.
      ' zzz specifies the full time zone offset.
      Dim format As [String] = "MM/dd/yyyy hh:mm:sszzz"

      ' Converts the local time to a string
      ' using the custom format string and display.
      Dim str As [String] = dt.ToString(format)
      Console.WriteLine(str)

      ' Converts the UTC time to a string
      ' using the custom format string and display.
      Dim utcstr As [String] = utcdt.ToString(format)
      Console.WriteLine(utcstr)

      ' Converts the string back to a local DateTime and displays it.
      Dim parsedBack As DateTime = DateTime.ParseExact(str, format, 
            en.DateTimeFormat)
      Console.WriteLine(parsedBack)

      ' Converts the string back to a UTC DateTime and displays it.
      ' If you do not use the DateTime.ParseExact method that takes
      ' a DateTimeStyles.AdjustToUniversal value, the parsed DateTime
      ' will not include the time zone information. 
      Dim parsedBackUTC As DateTime = DateTime.ParseExact(str, format, _
            en.DateTimeFormat, DateTimeStyles.AdjustToUniversal)
      Console.WriteLine(parsedBackUTC)
   End Sub
End Class
using System;
using System.Globalization;
using System.Threading;

public class TimeZoneSample
{
   public static void Main()
   {
      CultureInfo en = new CultureInfo("en-US");
      Thread.CurrentThread.CurrentCulture = en;

      // Creates a DateTime for the local time.
      DateTime dt = new DateTime(2001, 7, 13, 4, 0, 0);

      // Converts the local DateTime to the UTC time.
      DateTime utcdt = dt.ToUniversalTime();

      // Defines a custom string format to display the DateTime value.
      // zzzz specifies the full time zone offset.
      String format = "MM/dd/yyyy hh:mm:sszzz";

      // Converts the local DateTime to a string 
      // using the custom format string and display.
      String str = dt.ToString(format);
      Console.WriteLine(str);

      // Converts the UTC DateTime to a string 
      // using the custom format string and display.
      String utcstr = utcdt.ToString(format);
      Console.WriteLine(utcstr);

      // Converts the string back to a local DateTime and displays it.
      DateTime parsedBack =
            DateTime.ParseExact(str,format,en.DateTimeFormat);
      Console.WriteLine(parsedBack);

      // Converts the string back to a UTC DateTime and displays it.
      // If you do not use the DateTime.ParseExact method that takes
      // a DateTimeStyles.AdjustToUniversal value, the parsed DateTime
      // object will not include the time zone information.
      DateTime parsedBackUTC = DateTime.ParseExact(str,format, _
            en.DateTimeFormat, DateTimeStyles.AdjustToUniversal);
      Console.WriteLine(parsedBackUTC);
   }
}

このコードを実行すると、次の出力が生成されます。

07/13/2001 04:00:00-07:00
07/13/2001 11:00:00-07:00
7/13/2001 4:00:00 AM
7/13/2001 11:00:00 AM

DateTime のメンバの使用

DateTime 構造体を使用するときには、Day などのメンバがグレゴリオ暦に基づいている点に注意してください。アプリケーションが現在の暦を変更する場合やユーザーがコントロール パネルの [地域と言語のオプション] で日付と時刻の設定を変更できるようにする場合、DateTime のメソッドの計算処理にはグレゴリオ暦が使用されます。そのため、これらのメソッドが実行する算術演算処理がユーザーの設定によってエラーとなることはありません。アプリケーションで現在の暦に基づいてカルチャに依存した日付と時刻の処理を実行する場合は、Calendar プロパティを使用して Calendar クラスのメソッド (GetDayOfMonth など) を呼び出す必要があります。DateTime のメンバによって取得される値と Calendar のメンバによって取得される値の違いを示す例については、「固有カルチャに対応した暦の使用」を参照してください。

DateTime 構造体を使用するときには、DateTime 型が変更不可の値である点に注意してください。したがって AddDays などのメソッドは、既存の値を増分する代わりに、新しい DateTime 値を取得します。dt = dt.AddDays(1) というステートメントを使用して DateTime 型を 1 日増分する方法を次の例に示します。

Imports System
Imports System.Globalization
Imports System.Threading
Imports Microsoft.VisualBasic

Public Class TestClass
   
   Public Shared Sub Main()
      Thread.CurrentThread.CurrentCulture = New CultureInfo("en-US")
      
      Dim dt As DateTime = DateTime.Now
      Console.WriteLine(ControlChars.Newline + " Today is {0}", _
         DateTime.Now.ToString("d"))
      
      ' Increments dt by one day.
      dt = dt.AddDays(1)
      Console.WriteLine(ControlChars.Newline + " Tomorrow is {0}", _
         dt.ToString("d"))
   End Sub
End Class
using System;
using System.Globalization;
using System.Threading;

public class TestClass
{
   public static void Main()
   {
      Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US");

      DateTime dt = DateTime.Now;
      Console.WriteLine("Today is {0}", DateTime.Now.ToString("d"));

      // Increments dt by one day.
      dt = dt.AddDays(1);
      Console.WriteLine("Tomorrow is {0}", dt.ToString("d"));

   }
}

このコードを 2001 年 8 月 3 日に実行すると、出力は次のようになります。

Today is 8/3/2001
Tomorrow is 8/4/2001

参照

概念

日付と時刻の書式指定文字列

その他の技術情報

エンコーディングとローカリゼーション