カルチャ別の書式設定

ほとんどのメソッドでは、文字列書式指定子を使用して返される値を現在のカルチャまたは指定されたカルチャに基づいて変更できます。たとえば、ToString メソッドのオーバーロードは、IFormatProvider インターフェイスを実装する書式プロバイダを受け入れます。このインターフェイスを実装するクラスにより、小数点または桁区切り記号として使用する文字や、通貨記号のスペルと位置が指定されます。この書式プロバイダをパラメータとするオーバーライドを使用しない場合、ToString メソッドは現在のカルチャで指定されている文字を使用します。

CultureInfo クラスを使用して、ToString メソッドと書式指定文字列で使用されるカルチャを指定するコード例を次に示します。このコードでは、MyCulture という CultureInfo クラスの新しいインスタンスが作成され、fr-FR という文字列を使用してこのインスタンスが初期化され、カルチャが French に設定されます。フランスの通貨値を作成するため、文字列書式指定子 C と共にこのオブジェクトが ToString メソッドに渡されます。

Dim MyInt As Integer = 100
Dim MyCulture As New CultureInfo("fr-FR")
Dim MyString As String = MyInt.ToString("C", MyCulture)
Console.WriteLine(MyString)
int MyInt = 100;
CultureInfo MyCulture = new CultureInfo("fr-FR");
String MyString = MyInt.ToString("C", MyCulture);
Console.WriteLine(MyString);

上記のコードは、Windows フォームの形式では 100,00 と表示されます。コンソール環境では、Unicode 文字がサポートされていないため 100,00 ? と表示されます。

サポートされているカルチャの一覧については、CultureInfo クラスを参照してください。

現在のスレッドに関連付けられている CultureInfo オブジェクトの変更方法を示すコード例を次に示します。このコード例では、現在のスレッドに米国英語 (en-US) がカルチャとして関連付けられていることを前提としているため、このカルチャ (米国英語) を変更する方法が示されています。また、変更された CultureInfoToString メソッドに渡して特定のカルチャを指定する方法と、新しい DateTimeFormatInfoToString メソッドに渡す方法も示されています。

Dim dt As DateTime = DateTime.Now
Dim dfi As DateTimeFormatInfo = New DateTimeFormatInfo()
Dim ci As CultureInfo = New CultureInfo("de-DE")

' Create a new custom time pattern for demonstration.
dfi.MonthDayPattern = "MM-MMMM, ddd-dddd"

' Use the DateTimeFormat from the culture associated with 
' the current thread.

Console.WriteLine( dt.ToString("d") ) 
Console.WriteLine( dt.ToString("m") )

' Use the DateTimeFormat object from the specific culture passed.
Console.WriteLine( dt.ToString("d", ci ) )

' Use the settings from the DateTimeFormatInfo object passed.
Console.WriteLine( dt.ToString("m", dfi ) )

' Reset the current thread to a different culture.
Thread.CurrentThread.CurrentCulture = New CultureInfo("fr-BE")
Console.WriteLine( dt.ToString("d") )
DateTime dt = DateTime.Now;
DateTimeFormatInfo dfi = new DateTimeFormatInfo();
CultureInfo ci = new CultureInfo("de-DE");

// Create a new custom time pattern for demonstration.
dfi.MonthDayPattern = "MM-MMMM, ddd-dddd";

// Use the DateTimeFormat from the culture associated with 
// the current thread.
Console.WriteLine( dt.ToString("d") ); 
Console.WriteLine( dt.ToString("m") );

// Use the DateTimeFormat object from the specific culture passed.
Console.WriteLine( dt.ToString("d", ci ) );

// Use the settings from the DateTimeFormatInfo object passed.
Console.WriteLine( dt.ToString("m", dfi ) );

// Reset the current thread to a different culture.
Thread.CurrentThread.CurrentCulture = new CultureInfo("fr-BE");
Console.WriteLine( dt.ToString("d") );

参照

関連項目

System.IFormatProvider Interface
System.Globalization.CultureInfo Class

その他の技術情報

型の書式設定