DateTimeFormatInfo クラス
定義
重要
一部の情報は、リリース前に大きく変更される可能性があるプレリリースされた製品に関するものです。 Microsoft は、ここに記載されている情報について、明示または黙示を問わず、一切保証しません。
日付と時刻の値の書式に関するカルチャ固有の情報を提供します。
public ref class DateTimeFormatInfo sealed : IFormatProvider
public ref class DateTimeFormatInfo sealed : ICloneable, IFormatProvider
public ref class DateTimeFormatInfo sealed : ICloneable, IFormatProvider, System::Runtime::Serialization::ISerializable
public sealed class DateTimeFormatInfo : IFormatProvider
public sealed class DateTimeFormatInfo : ICloneable, IFormatProvider
[System.Serializable]
public sealed class DateTimeFormatInfo : ICloneable, IFormatProvider, System.Runtime.Serialization.ISerializable
[System.Serializable]
[System.Runtime.InteropServices.ComVisible(true)]
public sealed class DateTimeFormatInfo : ICloneable, IFormatProvider
type DateTimeFormatInfo = class
interface IFormatProvider
type DateTimeFormatInfo = class
interface ICloneable
interface IFormatProvider
[<System.Serializable>]
type DateTimeFormatInfo = class
interface ICloneable
interface IFormatProvider
interface ISerializable
[<System.Serializable>]
[<System.Runtime.InteropServices.ComVisible(true)>]
type DateTimeFormatInfo = class
interface ICloneable
interface IFormatProvider
Public NotInheritable Class DateTimeFormatInfo
Implements IFormatProvider
Public NotInheritable Class DateTimeFormatInfo
Implements ICloneable, IFormatProvider
Public NotInheritable Class DateTimeFormatInfo
Implements ICloneable, IFormatProvider, ISerializable
- 継承
-
DateTimeFormatInfo
- 属性
- 実装
例
次の例では、リフレクションを使用して、英語 (米国) カルチャの オブジェクトのDateTimeFormatInfoプロパティを取得します。 カスタム書式指定文字列を含むプロパティの値が表示され、それらの文字列を使用して書式設定された日付が表示されます。
using System;
using System.Globalization;
using System.Reflection;
public class Example
{
public static void Main()
{
// Get the properties of an en-US DateTimeFormatInfo object.
DateTimeFormatInfo dtfi = CultureInfo.GetCultureInfo("en-US").DateTimeFormat;
Type typ = dtfi.GetType();
PropertyInfo[] props = typ.GetProperties();
DateTime value = new DateTime(2012, 5, 28, 11, 35, 0);
foreach (var prop in props) {
// Is this a format pattern-related property?
if (prop.Name.Contains("Pattern")) {
string fmt = prop.GetValue(dtfi, null).ToString();
Console.WriteLine("{0,-33} {1} \n{2,-37}Example: {3}\n",
prop.Name + ":", fmt, "",
value.ToString(fmt));
}
}
}
}
// The example displays the following output:
// FullDateTimePattern: dddd, MMMM dd, yyyy h:mm:ss tt
// Example: Monday, May 28, 2012 11:35:00 AM
//
// LongDatePattern: dddd, MMMM dd, yyyy
// Example: Monday, May 28, 2012
//
// LongTimePattern: h:mm:ss tt
// Example: 11:35:00 AM
//
// MonthDayPattern: MMMM dd
// Example: May 28
//
// RFC1123Pattern: ddd, dd MMM yyyy HH':'mm':'ss 'GMT'
// Example: Mon, 28 May 2012 11:35:00 GMT
//
// ShortDatePattern: M/d/yyyy
// Example: 5/28/2012
//
// ShortTimePattern: h:mm tt
// Example: 11:35 AM
//
// SortableDateTimePattern: yyyy'-'MM'-'dd'T'HH':'mm':'ss
// Example: 2012-05-28T11:35:00
//
// UniversalSortableDateTimePattern: yyyy'-'MM'-'dd HH':'mm':'ss'Z'
// Example: 2012-05-28 11:35:00Z
//
// YearMonthPattern: MMMM, yyyy
// Example: May, 2012
Imports System.Globalization
Imports System.Reflection
Module Example
Public Sub Main()
' Get the properties of an en-US DateTimeFormatInfo object.
Dim dtfi As DateTimeFormatInfo = CultureInfo.GetCultureInfo("en-US").DateTimeFormat
Dim typ As Type = dtfi.GetType()
Dim props() As PropertyInfo = typ.GetProperties()
Dim value As Date = #05/28/2012 11:35AM#
For Each prop In props
' Is this a format pattern-related property?
If prop.Name.Contains("Pattern") Then
Dim fmt As String = CStr(prop.GetValue(dtfi, Nothing))
Console.WriteLine("{0,-33} {1} {2}{3,-37}Example: {4}",
prop.Name + ":", fmt, vbCrLf, "",
value.ToString(fmt))
Console.WriteLine()
End If
Next
End Sub
End Module
' The example displays the following output:
' FullDateTimePattern: dddd, MMMM dd, yyyy h:mm:ss tt
' Example: Monday, May 28, 2012 11:35:00 AM
'
' LongDatePattern: dddd, MMMM dd, yyyy
' Example: Monday, May 28, 2012
'
' LongTimePattern: h:mm:ss tt
' Example: 11:35:00 AM
'
' MonthDayPattern: MMMM dd
' Example: May 28
'
' RFC1123Pattern: ddd, dd MMM yyyy HH':'mm':'ss 'GMT'
' Example: Mon, 28 May 2012 11:35:00 GMT
'
' ShortDatePattern: M/d/yyyy
' Example: 5/28/2012
'
' ShortTimePattern: h:mm tt
' Example: 11:35 AM
'
' SortableDateTimePattern: yyyy'-'MM'-'dd'T'HH':'mm':'ss
' Example: 2012-05-28T11:35:00
'
' UniversalSortableDateTimePattern: yyyy'-'MM'-'dd HH':'mm':'ss'Z'
' Example: 2012-05-28 11:35:00Z
'
' YearMonthPattern: MMMM, yyyy
' Example: May, 2012
注釈
クラスのプロパティには、 DateTimeFormatInfo 次のような日付と時刻の値を書式設定または解析するためのカルチャ固有の情報が含まれています。
日付値の書式設定に使用されるパターン。
時刻値の書式設定に使用されるパターン。
曜日の名前。
年の月の名前。
時刻値で使用される午前と午後の指定子。
日付を表すカレンダー。
このセクションの内容は次のとおりです。
DateTimeFormatInfo オブジェクトのインスタンス化
オブジェクトは DateTimeFormatInfo 、インバリアント カルチャ、特定のカルチャ、ニュートラル カルチャ、または現在のカルチャの書式設定規則を表すことができます。 このセクションでは、オブジェクトの各種類 DateTimeFormatInfo をインスタンス化する方法について説明します。
インバリアント カルチャの DateTimeFormatInfo オブジェクトをインスタンス化する
インバリアント カルチャは、カルチャに依存しないカルチャを表します。 これは英語に基づいていますが、特定の英語を話す国/地域には基づいていません。 特定のカルチャのデータは動的であり、新しいカルチャ規則やユーザー設定を反映するように変更できますが、インバリアント カルチャのデータは変更されません。 インバリアント カルチャの DateTimeFormatInfo 書式設定規則を表す オブジェクトは、次の方法でインスタンス化できます。
プロパティの InvariantInfo 値を取得します。 返される DateTimeFormatInfo オブジェクトは読み取り専用です。
パラメーターなしの DateTimeFormatInfo コンストラクターを呼び出す。 返された DateTimeFormatInfo オブジェクトは読み取り/書き込み可能です。
プロパティによって返される オブジェクトから プロパティのDateTimeFormatCultureInfo値をCultureInfo.InvariantCulture取得します。 返される DateTimeFormatInfo オブジェクトは読み取り専用です。
次の例では、これらの各メソッドを使用して、インバリアント カルチャを DateTimeFormatInfo 表す オブジェクトをインスタンス化します。 その後、オブジェクトが読み取り専用かどうかを示します。
System.Globalization.DateTimeFormatInfo dtfi;
dtfi = System.Globalization.DateTimeFormatInfo.InvariantInfo;
Console.WriteLine(dtfi.IsReadOnly);
dtfi = new System.Globalization.DateTimeFormatInfo();
Console.WriteLine(dtfi.IsReadOnly);
dtfi = System.Globalization.CultureInfo.InvariantCulture.DateTimeFormat;
Console.WriteLine(dtfi.IsReadOnly);
// The example displays the following output:
// True
// False
// True
Dim dtfi As System.Globalization.DateTimeFormatInfo
dtfi = System.Globalization.DateTimeFormatInfo.InvariantInfo
Console.WriteLine(dtfi.IsReadOnly)
dtfi = New System.Globalization.DateTimeFormatInfo()
Console.WriteLine(dtfi.IsReadOnly)
dtfi = System.Globalization.CultureInfo.InvariantCulture.DateTimeFormat
Console.WriteLine(dtfi.IsReadOnly)
' The example displays the following output:
' True
' False
' True
特定のカルチャの DateTimeFormatInfo オブジェクトをインスタンス化する
特定のカルチャは、特定の国/地域で話される言語を表します。 たとえば、en-US は米国で話される英語を表す特定のカルチャであり、en-CA はカナダで話されている英語を表す特定のカルチャです。 次の方法で、 DateTimeFormatInfo 特定のカルチャの書式設定規則を表す オブジェクトをインスタンス化できます。
メソッドを CultureInfo.GetCultureInfo(String) 呼び出し、返された CultureInfo オブジェクト CultureInfo.DateTimeFormat の プロパティの値を取得します。 返される DateTimeFormatInfo オブジェクトは読み取り専用です。
静的 GetInstance メソッドを渡すことによって、 CultureInfo 取得するオブジェクトを持つ DateTimeFormatInfo カルチャを表す オブジェクト。 返された DateTimeFormatInfo オブジェクトは読み取り/書き込み可能です。
静的 CultureInfo.CreateSpecificCulture メソッドを呼び出し、返された CultureInfo オブジェクト CultureInfo.DateTimeFormat の プロパティの値を取得します。 返された DateTimeFormatInfo オブジェクトは読み取り/書き込み可能です。
クラス コンストラクターを CultureInfo.CultureInfo 呼び出し、返された CultureInfo オブジェクト CultureInfo.DateTimeFormat の プロパティの値を取得します。 返された DateTimeFormatInfo オブジェクトは読み取り/書き込み可能です。
次の例では、これらの各方法でオブジェクトをインスタンス化 DateTimeFormatInfo し、結果のオブジェクトが読み取り専用かどうかを示します。
System.Globalization.CultureInfo ci = null;
System.Globalization.DateTimeFormatInfo dtfi = null;
// Instantiate a culture using CreateSpecificCulture.
ci = System.Globalization.CultureInfo.CreateSpecificCulture("en-US");
dtfi = ci.DateTimeFormat;
Console.WriteLine("{0} from CreateSpecificCulture: {1}", ci.Name, dtfi.IsReadOnly);
// Instantiate a culture using the CultureInfo constructor.
ci = new System.Globalization.CultureInfo("en-CA");
dtfi = ci.DateTimeFormat;
Console.WriteLine("{0} from CultureInfo constructor: {1}", ci.Name, dtfi.IsReadOnly);
// Retrieve a culture by calling the GetCultureInfo method.
ci = System.Globalization.CultureInfo.GetCultureInfo("en-AU");
dtfi = ci.DateTimeFormat;
Console.WriteLine("{0} from GetCultureInfo: {1}", ci.Name, dtfi.IsReadOnly);
// Instantiate a DateTimeFormatInfo object by calling DateTimeFormatInfo.GetInstance.
ci = System.Globalization.CultureInfo.CreateSpecificCulture("en-GB");
dtfi = System.Globalization.DateTimeFormatInfo.GetInstance(ci);
Console.WriteLine("{0} from GetInstance: {1}", ci.Name, dtfi.IsReadOnly);
// The example displays the following output:
// en-US from CreateSpecificCulture: False
// en-CA from CultureInfo constructor: False
// en-AU from GetCultureInfo: True
// en-GB from GetInstance: False
Dim ci As System.Globalization.CultureInfo = Nothing
Dim dtfi As System.Globalization.DateTimeFormatInfo = Nothing
' Instantiate a culture using CreateSpecificCulture.
ci = System.Globalization.CultureInfo.CreateSpecificCulture("en-US")
dtfi = ci.DateTimeFormat
Console.WriteLine("{0} from CreateSpecificCulture: {1}", ci.Name, dtfi.IsReadOnly)
' Instantiate a culture using the CultureInfo constructor.
ci = new System.Globalization.CultureInfo("en-CA")
dtfi = ci.DateTimeFormat
Console.WriteLine("{0} from CultureInfo constructor: {1}", ci.Name, dtfi.IsReadOnly)
' Retrieve a culture by calling the GetCultureInfo method.
ci = System.Globalization.CultureInfo.GetCultureInfo("en-AU")
dtfi = ci.DateTimeFormat
Console.WriteLine("{0} from GetCultureInfo: {1}", ci.Name, dtfi.IsReadOnly)
' Instantiate a DateTimeFormatInfo object by calling DateTimeFormatInfo.GetInstance.
ci = System.Globalization.CultureInfo.CreateSpecificCulture("en-GB")
dtfi = System.Globalization.DateTimeFormatInfo.GetInstance(ci)
Console.WriteLine("{0} from GetInstance: {1}", ci.Name, dtfi.IsReadOnly)
' The example displays the following output:
' en-US from CreateSpecificCulture: False
' en-CA from CultureInfo constructor: False
' en-AU from GetCultureInfo: True
' en-GB from GetInstance: False
ニュートラル カルチャの DateTimeFormatInfo オブジェクトをインスタンス化する
ニュートラル カルチャは、国/地域に依存しないカルチャまたは言語を表します。通常、1 つ以上の特定のカルチャの親です。 たとえば、Fr はフランス語のニュートラル カルチャであり、fr-FR カルチャの親です。 ニュートラル カルチャの書式設定規則を DateTimeFormatInfo 表すオブジェクトは、特定のカルチャの書式設定規則を表すオブジェクトを作成 DateTimeFormatInfo するのと同じ方法でインスタンス化できます。 さらに、特定のカルチャのDateTimeFormatInfoプロパティからニュートラル カルチャを取得し、そのCultureInfo.DateTimeFormatプロパティによって返されるオブジェクトを取得することで、ニュートラル カルチャのCultureInfo.ParentオブジェクトをDateTimeFormatInfo取得できます。 親カルチャがインバリアント カルチャを表さない限り、返される DateTimeFormatInfo オブジェクトは読み取り/書き込みになります。 次の例は、ニュートラル カルチャを表すオブジェクトを DateTimeFormatInfo インスタンス化するこれらの方法を示しています。
System.Globalization.CultureInfo specific, neutral;
System.Globalization.DateTimeFormatInfo dtfi;
// Instantiate a culture by creating a specific culture and using its Parent property.
specific = System.Globalization.CultureInfo.GetCultureInfo("fr-FR");
neutral = specific.Parent;
dtfi = neutral.DateTimeFormat;
Console.WriteLine("{0} from Parent property: {1}", neutral.Name, dtfi.IsReadOnly);
dtfi = System.Globalization.CultureInfo.GetCultureInfo("fr-FR").Parent.DateTimeFormat;
Console.WriteLine("{0} from Parent property: {1}", neutral.Name, dtfi.IsReadOnly);
// Instantiate a neutral culture using the CultureInfo constructor.
neutral = new System.Globalization.CultureInfo("fr");
dtfi = neutral.DateTimeFormat;
Console.WriteLine("{0} from CultureInfo constructor: {1}", neutral.Name, dtfi.IsReadOnly);
// Instantiate a culture using CreateSpecificCulture.
neutral = System.Globalization.CultureInfo.CreateSpecificCulture("fr");
dtfi = neutral.DateTimeFormat;
Console.WriteLine("{0} from CreateSpecificCulture: {1}", neutral.Name, dtfi.IsReadOnly);
// Retrieve a culture by calling the GetCultureInfo method.
neutral = System.Globalization.CultureInfo.GetCultureInfo("fr");
dtfi = neutral.DateTimeFormat;
Console.WriteLine("{0} from GetCultureInfo: {1}", neutral.Name, dtfi.IsReadOnly);
// Instantiate a DateTimeFormatInfo object by calling GetInstance.
neutral = System.Globalization.CultureInfo.CreateSpecificCulture("fr");
dtfi = System.Globalization.DateTimeFormatInfo.GetInstance(neutral);
Console.WriteLine("{0} from GetInstance: {1}", neutral.Name, dtfi.IsReadOnly);
// The example displays the following output:
// fr from Parent property: False
// fr from Parent property: False
// fr from CultureInfo constructor: False
// fr-FR from CreateSpecificCulture: False
// fr from GetCultureInfo: True
// fr-FR from GetInstance: False
Dim specific, neutral As System.Globalization.CultureInfo
Dim dtfi As System.Globalization.DateTimeFormatInfo
' Instantiate a culture by creating a specific culture and using its Parent property.
specific = System.Globalization.CultureInfo.GetCultureInfo("fr-FR")
neutral = specific.Parent
dtfi = neutral.DateTimeFormat
Console.WriteLine("{0} from Parent property: {1}", neutral.Name, dtfi.IsReadOnly)
dtfi = System.Globalization.CultureInfo.GetCultureInfo("fr-FR").Parent.DateTimeFormat
Console.WriteLine("{0} from Parent property: {1}", neutral.Name, dtfi.IsReadOnly)
' Instantiate a neutral culture using the CultureInfo constructor.
neutral = New System.Globalization.CultureInfo("fr")
dtfi = neutral.DateTimeFormat
Console.WriteLine("{0} from CultureInfo constructor: {1}", neutral.Name, dtfi.IsReadOnly)
' Instantiate a culture using CreateSpecificCulture.
neutral = System.Globalization.CultureInfo.CreateSpecificCulture("fr")
dtfi = neutral.DateTimeFormat
Console.WriteLine("{0} from CreateSpecificCulture: {1}", neutral.Name, dtfi.IsReadOnly)
' Retrieve a culture by calling the GetCultureInfo method.
neutral = System.Globalization.CultureInfo.GetCultureInfo("fr")
dtfi = neutral.DateTimeFormat
Console.WriteLine("{0} from GetCultureInfo: {1}", neutral.Name, dtfi.IsReadOnly)
' Instantiate a DateTimeFormatInfo object by calling GetInstance.
neutral = System.Globalization.CultureInfo.CreateSpecificCulture("fr")
dtfi = System.Globalization.DateTimeFormatInfo.GetInstance(neutral)
Console.WriteLine("{0} from GetInstance: {1}", neutral.Name, dtfi.IsReadOnly)
' The example displays the following output:
' fr from Parent property: False
' fr from Parent property: False
' fr from CultureInfo constructor: False
' fr-FR from CreateSpecificCulture: False
' fr from GetCultureInfo: True
' fr-FR from GetInstance: False
Note
.NET Framework バージョン 1.0 から .NET Framework 3.5 では、ニュートラル カルチャの書式設定規則を反映するオブジェクトを取得DateTimeFormatInfoしようとすると、例外がNotSupportedExceptionスローされます。
ただし、ニュートラル カルチャでは、カルチャ固有の書式設定情報が不足しています。これは、特定の国/地域に依存しないためです。 オブジェクトにジェネリック値をDateTimeFormatInfo設定する代わりに、.NET Frameworkは、ニュートラル カルチャの子である特定のカルチャの書式設定規則を反映するオブジェクトを返DateTimeFormatInfoします。 たとえば、 DateTimeFormatInfo ニュートラル en カルチャの オブジェクトは en-US カルチャの書式設定規則を反映し DateTimeFormatInfo 、fr カルチャのオブジェクトには fr-FR カルチャの書式設定規則が反映されます。
次のようなコードを使用して、ニュートラル カルチャが表す特定のカルチャの書式設定規則を決定できます。 この例では、リフレクションを使用して、ニュートラル カルチャのプロパティと特定の子カルチャのプロパティを比較 DateTimeFormatInfo します。 2 つのカレンダーが同じカレンダーの種類である場合は同等と見なされ、グレゴリオ暦の場合はプロパティの GregorianCalendar.CalendarType 値が同じであると見なされます。
using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.Reflection;
public class Example
{
public static void Main()
{
// Get all the neutral cultures
List<String> names = new List<String>();
Array.ForEach(CultureInfo.GetCultures(CultureTypes.NeutralCultures),
culture => names.Add(culture.Name));
names.Sort();
foreach (var name in names) {
// Ignore the invariant culture.
if (name == "") continue;
ListSimilarChildCultures(name);
}
}
private static void ListSimilarChildCultures(String name)
{
// Create the neutral DateTimeFormatInfo object.
DateTimeFormatInfo dtfi = CultureInfo.GetCultureInfo(name).DateTimeFormat;
// Retrieve all specific cultures of the neutral culture.
CultureInfo[] cultures = Array.FindAll(CultureInfo.GetCultures(CultureTypes.SpecificCultures),
culture => culture.Name.StartsWith(name + "-", StringComparison.OrdinalIgnoreCase));
// Create an array of DateTimeFormatInfo properties
PropertyInfo[] properties = typeof(DateTimeFormatInfo).GetProperties(BindingFlags.Instance | BindingFlags.Public);
bool hasOneMatch = false;
foreach (var ci in cultures) {
bool match = true;
// Get the DateTimeFormatInfo for a specific culture.
DateTimeFormatInfo specificDtfi = ci.DateTimeFormat;
// Compare the property values of the two.
foreach (var prop in properties) {
// We're not interested in the value of IsReadOnly.
if (prop.Name == "IsReadOnly") continue;
// For arrays, iterate the individual elements to see if they are the same.
if (prop.PropertyType.IsArray) {
IList nList = (IList) prop.GetValue(dtfi, null);
IList sList = (IList) prop.GetValue(specificDtfi, null);
if (nList.Count != sList.Count) {
match = false;
Console.WriteLine(" Different n in {2} array for {0} and {1}", name, ci.Name, prop.Name);
break;
}
for (int ctr = 0; ctr < nList.Count; ctr++) {
if (! nList[ctr].Equals(sList[ctr])) {
match = false;
Console.WriteLine(" {0} value different for {1} and {2}", prop.Name, name, ci.Name);
break;
}
}
if (! match) break;
}
// Get non-array values.
else {
Object specificValue = prop.GetValue(specificDtfi);
Object neutralValue = prop.GetValue(dtfi);
// Handle comparison of Calendar objects.
if (prop.Name == "Calendar") {
// The cultures have a different calendar type.
if (specificValue.ToString() != neutralValue.ToString()) {
Console.WriteLine(" Different calendar types for {0} and {1}", name, ci.Name);
match = false;
break;
}
if (specificValue is GregorianCalendar) {
if (((GregorianCalendar) specificValue).CalendarType != ((GregorianCalendar) neutralValue).CalendarType) {
Console.WriteLine(" Different Gregorian calendar types for {0} and {1}", name, ci.Name);
match = false;
break;
}
}
}
else if (! specificValue.Equals(neutralValue)) {
match = false;
Console.WriteLine(" Different {0} values for {1} and {2}", prop.Name, name, ci.Name);
break;
}
}
}
if (match) {
Console.WriteLine("DateTimeFormatInfo object for '{0}' matches '{1}'",
name, ci.Name);
hasOneMatch = true;
}
}
if (! hasOneMatch)
Console.WriteLine("DateTimeFormatInfo object for '{0}' --> No Match", name);
Console.WriteLine();
}
}
Imports System.Collections
Imports System.Collections.Generic
Imports System.Globalization
Imports System.Reflection
Module Example
Public Sub Main()
' Get all the neutral cultures
Dim names As New List(Of String)
Array.ForEach(CultureInfo.GetCultures(CultureTypes.NeutralCultures),
Sub(culture) names.Add(culture.Name))
names.Sort()
For Each name In names
' Ignore the invariant culture.
If name = "" Then Continue For
ListSimilarChildCultures(name)
Next
End Sub
Private Sub ListSimilarChildCultures(name As String)
' Create the neutral DateTimeFormatInfo object.
Dim dtfi As DateTimeFormatInfo = CultureInfo.GetCultureInfo(name).DateTimeFormat
' Retrieve all specific cultures of the neutral culture.
Dim cultures() As CultureInfo = Array.FindAll(CultureInfo.GetCultures(CultureTypes.SpecificCultures),
Function(culture) culture.Name.StartsWith(name + "-", StringComparison.OrdinalIgnoreCase))
' Create an array of DateTimeFormatInfo properties
Dim properties() As PropertyInfo = GetType(DateTimeFormatInfo).GetProperties(BindingFlags.Instance Or BindingFlags.Public)
Dim hasOneMatch As Boolean = False
For Each ci In cultures
Dim match As Boolean = True
' Get the DateTimeFormatInfo for a specific culture.
Dim specificDtfi As DateTimeFormatInfo = ci.DateTimeFormat
' Compare the property values of the two.
For Each prop In properties
' We're not interested in the value of IsReadOnly.
If prop.Name = "IsReadOnly" Then Continue For
' For arrays, iterate the individual elements to see if they are the same.
If prop.PropertyType.IsArray Then
Dim nList As IList = CType(prop.GetValue(dtfi, Nothing), IList)
Dim sList As IList = CType(prop.GetValue(specificDtfi, Nothing), IList)
If nList.Count <> sList.Count Then
match = false
Console.WriteLine(" Different n in {2} array for {0} and {1}", name, ci.Name, prop.Name)
Exit For
End If
For ctr As Integer = 0 To nList.Count - 1
If Not nList(ctr).Equals(sList(ctr))
match = false
Console.WriteLine(" {0} value different for {1} and {2}", prop.Name, name, ci.Name)
Exit For
End If
Next
If Not match Then Exit For
' Get non-array values.
Else
Dim specificValue As Object = prop.GetValue(specificDtfi)
Dim neutralValue As Object = prop.GetValue(dtfi)
' Handle comparison of Calendar objects.
If prop.Name = "Calendar" Then
' The cultures have a different calendar type.
If specificValue.ToString() <> neutralValue.ToString() Then
Console.WriteLine(" Different calendar types for {0} and {1}", name, ci.Name)
match = False
Exit For
End If
If TypeOf specificValue Is GregorianCalendar Then
If CType(specificValue, GregorianCalendar).CalendarType <> CType(neutralValue, GregorianCalendar).CalendarType Then
Console.WriteLine(" Different Gregorian calendar types for {0} and {1}", name, ci.Name)
match = False
Exit For
End If
End If
Else If Not specificValue.Equals(neutralValue) Then
match = false
Console.WriteLine(" Different {0} values for {1} and {2}", prop.Name, name, ci.Name)
Exit For
End If
End If
Next
If match Then
Console.WriteLine("DateTimeFormatInfo object for '{0}' matches '{1}'",
name, ci.Name)
hasOneMatch = True
End If
Next
If Not hasOneMatch Then
Console.WriteLine("DateTimeFormatInfo object for '{0}' --> No Match", name)
End If
Console.WriteLine()
End Sub
End Module
現在のカルチャの DateTimeFormatInfo オブジェクトをインスタンス化する
現在のカルチャの DateTimeFormatInfo 書式設定規則を表す オブジェクトは、次の方法でインスタンス化できます。
プロパティの CurrentInfo 値を取得します。 返される DateTimeFormatInfo オブジェクトは読み取り専用です。
プロパティによって返される オブジェクトから プロパティのDateTimeFormatCultureInfo値をCultureInfo.CurrentCulture取得します。 返される DateTimeFormatInfo オブジェクトは読み取り専用です。
現在のカルチャを GetInstance 表す オブジェクトを CultureInfo 使用して メソッドを呼び出します。 返される DateTimeFormatInfo オブジェクトは読み取り専用です。
次の例では、これらの各メソッドを使用して、 DateTimeFormatInfo 現在のカルチャの書式設定規則を表す オブジェクトをインスタンス化します。 その後、オブジェクトが読み取り専用かどうかを示します。
DateTimeFormatInfo dtfi;
dtfi = DateTimeFormatInfo.CurrentInfo;
Console.WriteLine(dtfi.IsReadOnly);
dtfi = CultureInfo.CurrentCulture.DateTimeFormat;
Console.WriteLine(dtfi.IsReadOnly);
dtfi = DateTimeFormatInfo.GetInstance(CultureInfo.CurrentCulture);
Console.WriteLine(dtfi.IsReadOnly);
// The example displays the following output:
// True
// True
// True
Dim dtfi As DateTimeFormatInfo
dtfi = DateTimeFormatInfo.CurrentInfo
Console.WriteLine(dtfi.IsReadOnly)
dtfi = CultureInfo.CurrentCulture.DateTimeFormat
Console.WriteLine(dtfi.IsReadOnly)
dtfi = DateTimeFormatInfo.GetInstance(CultureInfo.CurrentCulture)
Console.WriteLine(dtfi.IsReadOnly)
' The example displays the following output:
' True
' True
' True
次のいずれかの方法で、現在のカルチャの規則を表す書き込み可能な DateTimeFormatInfo オブジェクトを作成できます。
前の 3 つの方法のいずれかでオブジェクトをDateTimeFormatInfo取得し、返されたDateTimeFormatInfoオブジェクトで Clone メソッドを呼び出します。 これにより、元 DateTimeFormatInfo のオブジェクトのコピーが作成されます。ただし、その IsReadOnly プロパティは です
false
。メソッドを CultureInfo.CreateSpecificCulture 呼び出して現在のカルチャを CultureInfo 表すオブジェクトを作成し、その CultureInfo.DateTimeFormat プロパティを使用してオブジェクトを DateTimeFormatInfo 取得します。
次の例では、読み取り/書き込 DateTimeFormatInfo みオブジェクトをインスタンス化する各方法を示し、その IsReadOnly プロパティの値を表示します。
using System;
using System.Globalization;
public class Example
{
public static void Main()
{
DateTimeFormatInfo current1 = DateTimeFormatInfo.CurrentInfo;
current1 = (DateTimeFormatInfo) current1.Clone();
Console.WriteLine(current1.IsReadOnly);
CultureInfo culture2 = CultureInfo.CreateSpecificCulture(CultureInfo.CurrentCulture.Name);
DateTimeFormatInfo current2 = culture2.DateTimeFormat;
Console.WriteLine(current2.IsReadOnly);
}
}
// The example displays the following output:
// False
// False
Imports System.Globalization
Module Example
Public Sub Main()
Dim current1 As DateTimeFormatInfo = DateTimeFormatInfo.CurrentInfo
current1 = CType(current1.Clone(), DateTimeFormatInfo)
Console.WriteLine(current1.IsReadOnly)
Dim culture2 As CultureInfo = CultureInfo.CreateSpecificCulture(CultureInfo.CurrentCulture.Name)
Dim current2 As DateTimeFormatInfo = culture2.DateTimeFormat
Console.WriteLine(current2.IsReadOnly)
End Sub
End Module
' The example displays the following output:
' False
' False
Windows では、ユーザーは、コントロール パネルの DateTimeFormatInfoRegion および Language アプリケーションを使用して、書式設定および解析操作で使用されるプロパティ値の一部をオーバーライドできます。 たとえば、カルチャが英語 (米国) のユーザーは、既定の 12 時間制 (h:mm:ss tt 形式) ではなく、24 時間制 (HH:mm:ss 形式) を使用して長い時間値を表示することを選択できます。 前に説明した方法で取得されたオブジェクトには DateTimeFormatInfo 、これらのユーザーのオーバーライドがすべて反映されます。 これが望ましくない場合は、コンストラクターを NumberFormatInfo 呼び出 CultureInfo.CultureInfo(String, Boolean) し、 引数に の値 false
を指定することで、ユーザーのオーバーライドを反映しないオブジェクト (および読み取り専用ではなく読み取り/書き込みも可能) を useUserOverride
作成できます。 次の例は、現在のカルチャが英語 (米国) で、長い時間パターンが既定の h:mm:ss tt から HH:mm:ss に変更されたシステムについて、これを示しています。
using System;
using System.Globalization;
public class Example
{
public static void Main()
{
CultureInfo culture;
DateTimeFormatInfo dtfi;
culture = CultureInfo.CurrentCulture;
dtfi = culture.DateTimeFormat;
Console.WriteLine("Culture Name: {0}", culture.Name);
Console.WriteLine("User Overrides: {0}", culture.UseUserOverride);
Console.WriteLine("Long Time Pattern: {0}\n", culture.DateTimeFormat.LongTimePattern);
culture = new CultureInfo(CultureInfo.CurrentCulture.Name, false);
Console.WriteLine("Culture Name: {0}", culture.Name);
Console.WriteLine("User Overrides: {0}", culture.UseUserOverride);
Console.WriteLine("Long Time Pattern: {0}\n", culture.DateTimeFormat.LongTimePattern);
}
}
// The example displays the following output:
// Culture Name: en-US
// User Overrides: True
// Long Time Pattern: HH:mm:ss
//
// Culture Name: en-US
// User Overrides: False
// Long Time Pattern: h:mm:ss tt
Imports System.Globalization
Module Example
Public Sub Main()
Dim culture As CultureInfo
Dim dtfi As DateTimeFormatInfo
culture = CultureInfo.CurrentCulture
dtfi = culture.DateTimeFormat
Console.WriteLine("Culture Name: {0}", culture.Name)
Console.WriteLine("User Overrides: {0}", culture.UseUserOverride)
Console.WriteLine("Long Time Pattern: {0}", culture.DateTimeFormat.LongTimePattern)
Console.WriteLine()
culture = New CultureInfo(CultureInfo.CurrentCulture.Name, False)
Console.WriteLine("Culture Name: {0}", culture.Name)
Console.WriteLine("User Overrides: {0}", culture.UseUserOverride)
Console.WriteLine("Long Time Pattern: {0}", culture.DateTimeFormat.LongTimePattern)
End Sub
End Module
' The example displays the following output:
' Culture Name: en-US
' User Overrides: True
' Long Time Pattern: HH:mm:ss
'
' Culture Name: en-US
' User Overrides: False
' Long Time Pattern: h:mm:ss tt
DateTimeFormatInfo と動的データ
クラスによって提供される日付と時刻の値を書式設定するためのカルチャ固有の DateTimeFormatInfo データは、クラスによって提供されるカルチャ データと同様に CultureInfo 動的です。 特定CultureInfoのオブジェクトに関連付けられているオブジェクトの値DateTimeFormatInfoの安定性については、何も想定しないでください。 インバリアント カルチャとそれに関連付けられている DateTimeFormatInfo オブジェクトによって提供されるデータのみが安定しています。 その他のデータは、アプリケーション セッション間、またはアプリケーションの実行中に変更される可能性があります。 大きな変化の原因は 4 つあります。
システムの更新。 優先カレンダーや慣例の日付と時刻の形式などの文化的な好みは、時間の経過と同時に変化します。 この場合、Windows Updateには、特定のカルチャのDateTimeFormatInfoプロパティ値に対する変更が含まれます。
置換カルチャ。 クラスを CultureAndRegionInfoBuilder 使用して、既存のカルチャのデータを置き換えることができます。
プロパティ値に対するカスケード変更。 カルチャ関連のプロパティの数は実行時に変更される可能性があり、その結果、データが DateTimeFormatInfo 変更されます。 たとえば、現在のカルチャは、プログラムまたはユーザー アクションを使用して変更できます。 この場合、 DateTimeFormatInfo プロパティによって返されるオブジェクトは、現在の CurrentInfo カルチャに関連付けられているオブジェクトに変更されます。 同様に、カルチャのカレンダーを変更すると、多数 DateTimeFormatInfo のプロパティ値が変更される可能性があります。
ユーザー設定。 アプリケーションのユーザーは、コントロール パネルの地域と言語のオプションを使用して、現在のシステム カルチャに関連付けられている値の一部をオーバーライドすることを選択できます。 たとえば、ユーザーは別の形式で日付を表示することを選択できます。 プロパティが CultureInfo.UseUserOverride に
true
設定されている場合、オブジェクトの DateTimeFormatInfo プロパティもユーザー設定から取得されます。 ユーザー設定がオブジェクトに関連付 CultureInfo けられているカルチャと互換性がない場合 (たとえば、選択した予定表が プロパティによって OptionalCalendars 示されるカレンダーの 1 つではない場合)、メソッドの結果とプロパティの値は未定義です。
不整合なデータの可能性を最小限に抑えるために、オブジェクトのユーザーオーバーライド可能なプロパティはすべて、オブジェクトの DateTimeFormatInfo 作成時に初期化されます。 オブジェクトの作成もユーザーオーバーライドプロセスもアトミックでなく、オブジェクトの作成時に関連する値が変更される可能性があるため、不整合が発生する可能性があります。 ただし、この状況は非常にまれである必要があります。
システム カルチャと同じカルチャを表すオブジェクトに DateTimeFormatInfo ユーザーオーバーライドを反映するかどうかを制御できます。 次の表は、オブジェクトを取得する方法を DateTimeFormatInfo 示し、結果のオブジェクトにユーザーのオーバーライドが反映されるかどうかを示します。
CultureInfo オブジェクトと DateTimeFormatInfo オブジェクトのソース | ユーザーのオーバーライドを反映します |
---|---|
CultureInfo.CurrentCulture.DateTimeFormat プロパティ |
はい |
DateTimeFormatInfo.CurrentInfo プロパティ | はい |
CultureInfo.CreateSpecificCulture メソッド | はい |
CultureInfo.GetCultureInfo メソッド | いいえ |
CultureInfo.CultureInfo(String) コンストラクター | はい |
CultureInfo.CultureInfo(String, Boolean) コンストラクター | パラメーターの useUserOverride 値によって異なります |
他の操作を行う説得力のある理由がない限り、クライアント アプリケーションで オブジェクトを使用 DateTimeFormatInfo してユーザー入力の書式設定と解析を行ったり、データを表示したりする場合は、ユーザーオーバーライドを考慮する必要があります。 サーバー アプリケーションまたは無人アプリケーションの場合は、しないでください。 ただし、 オブジェクトを DateTimeFormatInfo 明示的または暗黙的に使用して日付と時刻のデータを文字列形式で保持する場合は、インバリアント カルチャの書式設定規則を反映するオブジェクトを使用 DateTimeFormatInfo するか、カルチャに関係なく使用するカスタムの日付と時刻書式指定文字列を指定する必要があります。
日付と時刻の書式設定
DateTimeFormatInfoオブジェクトは、すべての日付と時刻の書式設定操作で暗黙的または明示的に使用されます。 これには、次のメソッドの呼び出しが含まれます。
や DateTimeOffset.ToString(String)などDateTime.ToString()、すべての日付と時刻の書式設定メソッド。
主要な複合書式指定メソッド 。これは です String.Format。
その他の複合書式指定メソッド (や StringBuilder.AppendFormat(String, Object[])などConsole.WriteLine(String, Object[]))。
すべての日付と時刻の書式設定操作では、実装が IFormatProvider 使用されます。 インターフェイスには IFormatProvider 、 という 1 つのメソッドが IFormatProvider.GetFormat(Type)含まれています。 このコールバック メソッドには、書式設定情報を Type 提供するために必要な型を表す オブジェクトが渡されます。 メソッドは、その型のインスタンスを返すか null
、型のインスタンスを指定できない場合は を返します。 .NET Frameworkには、日付と時刻を書式設定するための 2 つのIFormatProvider実装が含まれています。
クラス。 CultureInfo 特定のカルチャ (または特定の国/地域の特定の言語) を表します。 日付と時刻の書式設定操作では、 メソッドはCultureInfo.GetFormat、そのプロパティに関連付けられているオブジェクトをCultureInfo.DateTimeFormatDateTimeFormatInfo返します。
クラス。このクラスは DateTimeFormatInfo 、関連付けられたカルチャの書式設定規則に関する情報を提供します。 メソッドは DateTimeFormatInfo.GetFormat それ自体のインスタンスを返します。
実装が IFormatProvider 書式設定メソッドに明示的に指定されていない場合は、現在のカルチャを CultureInfo 表す プロパティによって CultureInfo.CurrentCulture 返されるオブジェクトが使用されます。
次の例は、書式設定操作における IFormatProvider インターフェイスと クラスの DateTimeFormatInfo 関係を示しています。 このメソッドは、書式設定操作によって要求されたオブジェクトの型を表示するカスタム IFormatProvider 実装 GetFormat を定義します。 オブジェクトを要求している DateTimeFormatInfo 場合、 メソッドは現在のカルチャの DateTimeFormatInfo オブジェクトを提供します。 この例の出力に示すように、 メソッドはDecimal.ToString(IFormatProvider)オブジェクトに書式情報を提供するように要求DateTimeFormatInfoしますがString.Format(IFormatProvider, String, Object[])、メソッドは、実装だけでなくICustomFormatter、オブジェクトもDateTimeFormatInfo要求NumberFormatInfoします。
using System;
using System.Globalization;
public class CurrentCultureFormatProvider : IFormatProvider
{
public Object GetFormat(Type formatType)
{
Console.WriteLine("Requesting an object of type {0}",
formatType.Name);
if (formatType == typeof(NumberFormatInfo))
return NumberFormatInfo.CurrentInfo;
else if (formatType == typeof(DateTimeFormatInfo))
return DateTimeFormatInfo.CurrentInfo;
else
return null;
}
}
public class Example
{
public static void Main()
{
DateTime dateValue = new DateTime(2013, 5, 28, 13, 30, 0);
string value = dateValue.ToString("F", new CurrentCultureFormatProvider());
Console.WriteLine(value);
Console.WriteLine();
string composite = String.Format(new CurrentCultureFormatProvider(),
"Date: {0:d} Amount: {1:C} Description: {2}",
dateValue, 1264.03m, "Service Charge");
Console.WriteLine(composite);
Console.WriteLine();
}
}
// The example displays output like the following:
// Requesting an object of type DateTimeFormatInfo
// Tuesday, May 28, 2013 1:30:00 PM
//
// Requesting an object of type ICustomFormatter
// Requesting an object of type DateTimeFormatInfo
// Requesting an object of type NumberFormatInfo
// Date: 5/28/2013 Amount: $1,264.03 Description: Service Charge
Imports System.Globalization
Public Class CurrentCultureFormatProvider : Implements IFormatProvider
Public Function GetFormat(formatType As Type) As Object _
Implements IFormatProvider.GetFormat
Console.WriteLine("Requesting an object of type {0}",
formatType.Name)
If formatType Is GetType(NumberFormatInfo) Then
Return NumberFormatInfo.CurrentInfo
Else If formatType Is GetType(DateTimeFormatInfo) Then
Return DateTimeFormatInfo.CurrentInfo
Else
Return Nothing
End If
End Function
End Class
Module Example
Public Sub Main()
Dim dateValue As New Date(2013, 05, 28, 13, 30, 0)
Dim value As String = dateValue.ToString("F", New CurrentCultureFormatProvider())
Console.WriteLine(value)
Console.WriteLine()
Dim composite As String = String.Format(New CurrentCultureFormatProvider,
"Date: {0:d} Amount: {1:C} Description: {2}",
dateValue, 1264.03d, "Service Charge")
Console.WriteLine(composite)
Console.WriteLine()
End Sub
End Module
' The example displays output like the following:
' Requesting an object of type DateTimeFormatInfo
' Tuesday, May 28, 2013 1:30:00 PM
'
' Requesting an object of type ICustomFormatter
' Requesting an object of type DateTimeFormatInfo
' Requesting an object of type NumberFormatInfo
' Date: 5/28/2013 Amount: $1,264.03 Description: Service Charge
文字列と DateTimeFormatInfo プロパティの書式設定
オブジェクトには DateTimeFormatInfo 、日付と時刻の値を使用した書式設定操作で使用される 3 種類のプロパティが含まれています。
予定表関連のプロパティ。 、 などのAbbreviatedDayNamesMonthNamesAbbreviatedMonthNamesDayNamesプロパティは、 プロパティによって定義されるカルチャで使用されるカレンダーにCalendar関連付けられます。 これらのプロパティは、長い日付と時刻の形式に使用されます。
標準定義の結果文字列を生成するプロパティ。 、RFC1123PatternSortableDateTimePattern、および プロパティには、UniversalSortableDateTimePattern国際標準で定義された結果文字列を生成するカスタム書式指定文字列が含まれています。 これらのプロパティは読み取り専用であり、変更できません。
カルチャに依存する結果文字列を定義するプロパティ。 や ShortDatePatternなどのFullDateTimePattern一部のプロパティには、結果文字列の形式を指定するカスタム書式指定文字列が含まれています。 、、 などのAMDesignatorDateSeparatorPMDesignatorTimeSeparator他のユーザーは、カルチャに依存するシンボルまたは結果文字列に含めることができる部分文字列を定義します。
"d"、"D"、"f"、"F" などの 標準の日付と時刻の書式指定文字列は、特定 DateTimeFormatInfo の書式パターンプロパティに対応するエイリアスです。 カスタムの日付と時刻の書式指定文字列のほとんどは、書式設定操作によって結果ストリームに挿入される文字列または部分文字列に関連しています。 次の表に、標準およびカスタムの日付と時刻の書式指定子とそれに関連付けられている DateTimeFormatInfo プロパティを示します。 これらの書式指定子の使用方法の詳細については、「 標準の日付と時刻の書式指定文字列」および 「 カスタムの日付と時刻の書式指定文字列」を参照してください。 各標準書式指定文字列は、値がカスタムの日時書式指定文字列であるプロパティに対応 DateTimeFormatInfo します。 このカスタム書式指定文字列の個々の指定子は、他 DateTimeFormatInfo のプロパティに対応します。 この表には、標準書式指定文字列がエイリアスであるプロパティのみが DateTimeFormatInfo 一覧表示され、それらの別名付きプロパティに割り当てられたカスタム書式指定文字列によってアクセスされる可能性があるプロパティは一覧表示されません。 また、この表には、プロパティに対応 DateTimeFormatInfo するカスタム書式指定子のみが一覧表示されます。
書式指定子 | 関連付けられたプロパティ |
---|---|
"d" (短い日付;標準書式指定文字列) | ShortDatePattern: 結果文字列の全体的な形式を定義します。 |
"D" (長い日付;標準書式指定文字列) | LongDatePattern: 結果文字列の全体的な形式を定義します。 |
"f" (完全な日付/短い時刻;標準書式指定文字列) | LongDatePattern: 結果文字列の日付コンポーネントの形式を定義します。 ShortTimePattern: 結果文字列の時刻コンポーネントの形式を定義します。 |
"F" (完全な日付/長い時間;標準書式指定文字列) | LongDatePattern: 結果文字列の日付コンポーネントの形式を定義します。 LongTimePattern: 結果文字列の時刻コンポーネントの形式を定義します。 |
"g" (一般的な日付/短い時刻;標準書式指定文字列) | ShortDatePattern: 結果文字列の日付コンポーネントの形式を定義します。 ShortTimePattern: 結果文字列の時刻コンポーネントの形式を定義します。 |
"G" (一般的な日付/長い時間;標準書式指定文字列) | ShortDatePattern: 結果文字列の日付コンポーネントの形式を定義します。 LongTimePattern: 結果文字列の時刻コンポーネントの形式を定義します。 |
"M"、"m" (月/日;標準書式指定文字列) | MonthDayPattern: 結果文字列の全体的な形式を定義します。 |
"O"、"o" (ラウンドトリップ日時、標準書式指定文字列) | [なし] : |
"R"、"r" (RFC1123;標準書式指定文字列) | RFC1123PatternRFC 1123 標準に準拠する結果文字列を定義します。 このプロパティは読み取り専用です。 |
"s" (並べ替え可能な日付/時刻、標準書式指定文字列) | SortableDateTimePatternは、ISO 8601 標準に準拠する結果文字列を定義します。 このプロパティは読み取り専用です。 |
"t" (短い時刻;標準書式指定文字列) | ShortTimePattern: 結果文字列の全体的な形式を定義します。 |
"T" (長い時間;標準書式指定文字列) | LongTimePattern: 結果文字列の全体的な形式を定義します。 |
"u" (汎用並べ替え可能な日付/時刻;標準書式指定文字列) | UniversalSortableDateTimePatternは、協定世界時の ISO 8601 標準に準拠する結果文字列を定義します。 このプロパティは読み取り専用です。 |
"U" (ユニバーサル完全な日付/時刻;標準書式指定文字列) | FullDateTimePattern: 結果文字列の全体的な形式を定義します。 |
"Y"、"y" (年月;標準書式指定文字列) | YearMonthPattern: 結果文字列の全体的な形式を定義します。 |
"ddd" (カスタム書式指定子) | AbbreviatedDayNames: 結果文字列に曜日の省略名を含めます。 |
"g"、"gg" (カスタム書式指定子) | メソッドを GetEraName 呼び出して、結果文字列に時代 (年号) の名前を挿入します。 |
"MMM" (カスタム書式指定子) | AbbreviatedMonthNamesは、結果文字列に省略された月の名前を含めます。 |
"MMMM" (カスタム書式指定子) | MonthNames または MonthGenitiveNames、 を指定して、結果文字列に完全な月名を含めます。 |
"t" (カスタム書式指定子) | AMDesignator または PMDesignator、AM/PM 指定子の最初の文字を結果文字列に含めます。 |
"tt" (カスタム書式指定子) | AMDesignator または PMDesignator、完全な AM/PM 指定子を結果文字列に含めます。 |
":" (カスタム書式指定子) | TimeSeparator: 結果文字列に時刻区切り記号を含めます。 |
"/" (カスタム書式指定子) | DateSeparator: 結果文字列に日付区切り記号を含めます。 |
DateTimeFormatInfo プロパティの変更
日付と時刻の書式指定文字列によって生成される結果文字列を変更するには、書き込み可能な DateTimeFormatInfo オブジェクトの関連付けられているプロパティを変更します。 オブジェクトが DateTimeFormatInfo 書き込み可能かどうかを判断するには、 プロパティを使用します IsReadOnly 。 この方法でオブジェクトを DateTimeFormatInfo カスタマイズするには:
書式設定規則を変更する DateTimeFormatInfo オブジェクトの読み取り/書き込みコピーを作成します。 (「 DateTimeFormatInfo オブジェクトのインスタンス化 」セクションを参照してください)。
目的の結果文字列を生成するために使用されるプロパティを変更します。 (書式設定メソッドでプロパティを使用 DateTimeFormatInfo して結果文字列を定義する方法については、前のセクション「 文字列の書式設定」と「DateTimeFormatInfo プロパティ」を参照してください)。
書式設定メソッドの呼び出しで、 IFormatProvider 引数として作成したカスタム DateTimeFormatInfo オブジェクトを使用します。
結果文字列の形式を変更するには、他に 2 つの方法があります。
クラスを CultureAndRegionInfoBuilder 使用して、カスタム カルチャ (一意の名前を持ち、既存のカルチャを補完するカルチャ) または置換カルチャ (特定のカルチャの代わりに使用されるカルチャ) を定義できます。 .NET Frameworkでサポートされているオブジェクトと同様CultureInfoに、プログラムでこのカルチャを保存してアクセスできます。
結果文字列がカルチャに依存せず、定義済みの形式に従っていない場合は、カスタムの日時書式指定文字列を使用できます。 たとえば、日付と時刻のデータを YYYYMMDDHHmmss 形式でシリアル化する場合は、カスタム書式指定文字列を メソッドにDateTime.ToString(String)渡すことで結果文字列を生成し、 メソッドを呼び出DateTime.ParseExactして結果文字列を値にDateTime変換できます。
短い日付パターンの変更
次の例では、"d" (短い日付) 標準書式指定文字列によって生成される結果文字列の形式を変更します。 en-US または英語 (米国) カルチャの関連付けられたShortDatePatternプロパティを既定の "M/d/yyyy" から "y'-"MM"-"dd" に変更し、"d" 標準書式指定文字列を使用して、プロパティが変更される前後ShortDatePatternの日付を表示します。
using System;
using System.Globalization;
public class Example
{
public static void Main()
{
DateTime dateValue = new DateTime(2013, 8, 18);
CultureInfo enUS = CultureInfo.CreateSpecificCulture("en-US");
DateTimeFormatInfo dtfi = enUS.DateTimeFormat;
Console.WriteLine("Before modifying DateTimeFormatInfo object: ");
Console.WriteLine("{0}: {1}\n", dtfi.ShortDatePattern,
dateValue.ToString("d", enUS));
// Modify the short date pattern.
dtfi.ShortDatePattern = "yyyy-MM-dd";
Console.WriteLine("After modifying DateTimeFormatInfo object: ");
Console.WriteLine("{0}: {1}", dtfi.ShortDatePattern,
dateValue.ToString("d", enUS));
}
}
// The example displays the following output:
// Before modifying DateTimeFormatInfo object:
// M/d/yyyy: 8/18/2013
//
// After modifying DateTimeFormatInfo object:
// yyyy-MM-dd: 2013-08-18
Imports System.Globalization
Module Example
Public Sub Main()
Dim dateValue As New Date(2013, 08, 18)
Dim enUS As CultureInfo = CultureInfo.CreateSpecificCulture("en-US")
Dim dtfi As DateTimeFormatInfo = enUS.DateTimeFormat
Console.WriteLine("Before modifying DateTimeFormatInfo object: ")
Console.WriteLine("{0}: {1}", dtfi.ShortDatePattern,
dateValue.ToString("d", enUS))
Console.WriteLine()
' Modify the short date pattern.
dtfi.ShortDatePattern = "yyyy-MM-dd"
Console.WriteLine("After modifying DateTimeFormatInfo object: ")
Console.WriteLine("{0}: {1}", dtfi.ShortDatePattern,
dateValue.ToString("d", enUS))
End Sub
End Module
' The example displays the following output:
' Before modifying DateTimeFormatInfo object:
' M/d/yyyy: 8/18/2013
'
' After modifying DateTimeFormatInfo object:
' yyyy-MM-dd: 2013-08-18
日付区切り文字の変更
次の例では、fr-FR カルチャの書式設定規則を DateTimeFormatInfo 表す オブジェクトの日付区切り文字を変更します。 この例では、"g" 標準書式指定文字列を使用して、 プロパティが変更される前と後の両方の日付を DateSeparator 表示します。
using System;
using System.Globalization;
public class Example
{
public static void Main()
{
DateTime dateValue = new DateTime(2013, 08, 28);
CultureInfo frFR = CultureInfo.CreateSpecificCulture("fr-FR");
DateTimeFormatInfo dtfi = frFR.DateTimeFormat;
Console.WriteLine("Before modifying DateSeparator property: {0}",
dateValue.ToString("g", frFR));
// Modify the date separator.
dtfi.DateSeparator = "-";
Console.WriteLine("After modifying the DateSeparator property: {0}",
dateValue.ToString("g", frFR));
}
}
// The example displays the following output:
// Before modifying DateSeparator property: 28/08/2013 00:00
// After modifying the DateSeparator property: 28-08-2013 00:00
Imports System.Globalization
Module Example
Public Sub Main()
Dim dateValue As New Date(2013, 08, 28)
Dim frFR As CultureInfo = CultureInfo.CreateSpecificCulture("fr-FR")
Dim dtfi As DateTimeFormatInfo = frFR.DateTimeFormat
Console.WriteLine("Before modifying DateSeparator property: {0}",
dateValue.ToString("g", frFR))
' Modify the date separator.
dtfi.DateSeparator = "-"
Console.WriteLine("After modifying the DateSeparator property: {0}",
dateValue.ToString("g", frFR))
End Sub
End Module
' The example displays the following output:
' Before modifying DateSeparator property: 28/08/2013 00:00
' After modifying the DateSeparator property: 28-08-2013 00:00
曜日名の省略形と長い日付パターンの変更
場合によっては、通常、完全な日と月の名前を月の日付と年の数と共に表示する長い日付パターンが長すぎる可能性があります。 次の例では、en-US カルチャの長い日付パターンを短くして、1 文字または 2 文字の日の名前の省略形を返し、その後に日番号、月名の省略形、および年を返します。 これは、短い曜日名の省略形を配列に割り当て、プロパティに AbbreviatedDayNames 割り当てられたカスタム書式指定文字列を LongDatePattern 変更することによって行われます。 これは、"D" および "f" 標準書式指定文字列によって返される結果文字列に影響します。
using System;
using System.Globalization;
public class Example
{
public static void Main()
{
DateTime value = new DateTime(2013, 7, 9);
CultureInfo enUS = CultureInfo.CreateSpecificCulture("en-US");
DateTimeFormatInfo dtfi = enUS.DateTimeFormat;
String[] formats = { "D", "F", "f" };
// Display date before modifying properties.
foreach (var fmt in formats)
Console.WriteLine("{0}: {1}", fmt, value.ToString(fmt, dtfi));
Console.WriteLine();
// We don't want to change the FullDateTimePattern, so we need to save it.
String originalFullDateTimePattern = dtfi.FullDateTimePattern;
// Modify day name abbreviations and long date pattern.
dtfi.AbbreviatedDayNames = new String[] { "Su", "M", "Tu", "W", "Th", "F", "Sa" };
dtfi.LongDatePattern = "ddd dd-MMM-yyyy";
dtfi.FullDateTimePattern = originalFullDateTimePattern;
foreach (var fmt in formats)
Console.WriteLine("{0}: {1}", fmt, value.ToString(fmt, dtfi));
}
}
// The example displays the following output:
// D: Tuesday, July 9, 2013
// F: Tuesday, July 9, 2013 12:00:00 AM
// f: Tuesday, July 9, 2013 12:00 AM
//
// D: Tu 09-Jul-2013
// F: Tuesday, July 9, 2013 12:00:00 AM
// f: Tu 09-Jul-2013 12:00 AM
Imports System.Globalization
Module Example
Public Sub Main()
Dim value As New Date(2013, 7, 9)
Dim enUS As CultureInfo = CultureInfo.CreateSpecificCulture("en-US")
Dim dtfi As DateTimeFormatInfo = enUS.DateTimeFormat
Dim formats() As String = { "D", "F", "f" }
' Display date before modifying properties.
For Each fmt In formats
Console.WriteLine("{0}: {1}", fmt, value.ToString(fmt, dtfi))
Next
Console.WriteLine()
' We don't want to change the FullDateTimePattern, so we need to save it.
Dim originalFullDateTimePattern As String = dtfi.FullDateTimePattern
' Modify day name abbreviations and long date pattern.
dtfi.AbbreviatedDayNames = { "Su", "M", "Tu", "W", "Th", "F", "Sa" }
dtfi.LongDatePattern = "ddd dd-MMM-yyyy"
dtfi.FullDateTimePattern = originalFullDateTimePattern
For Each fmt In formats
Console.WriteLine("{0}: {1}", fmt, value.ToString(fmt, dtfi))
Next
End Sub
End Module
' The example displays the following output:
' D: Tuesday, July 9, 2013
' F: Tuesday, July 9, 2013 12:00:00 AM
' f: Tuesday, July 9, 2013 12:00 AM
'
' D: Tu 09-Jul-2013
' F: Tuesday, July 9, 2013 12:00:00 AM
' f: Tu 09-Jul-2013 12:00 AM
通常、プロパティに対する LongDatePattern 変更は プロパティにも影響 FullDateTimePattern します。これにより、"F" 標準書式指定文字列によって返される結果文字列が定義されます。 元の完全な日付と時刻のパターンを保持するために、プロパティが変更された後、プロパティに割り当てられた元の FullDateTimePattern カスタム書式指定文字列を LongDatePattern 再割り当てします。
12 時間制から 24 時間制に変更する
.NET Frameworkの多くのカルチャでは、時刻は 12 時間制と AM/PM 指定子を使用して表されます。 次の例では、 ReplaceWith24HourClock
12 時間制を使用する任意の時刻形式を 24 時間制の形式に置き換えるメソッドを定義しています。
using System;
using System.Globalization;
using System.Text.RegularExpressions;
public class Example
{
public static void Main()
{
CultureInfo enUS = CultureInfo.CreateSpecificCulture("en-US");
DateTimeFormatInfo dtfi = enUS.DateTimeFormat;
Console.WriteLine("Original Property Values:");
Console.WriteLine("ShortTimePattern: " + dtfi.ShortTimePattern);
Console.WriteLine("LongTimePattern: " + dtfi.LongTimePattern);
Console.WriteLine("FullDateTimePattern: " + dtfi.FullDateTimePattern);
Console.WriteLine();
dtfi.LongTimePattern = ReplaceWith24HourClock(dtfi.LongTimePattern);
dtfi.ShortTimePattern = ReplaceWith24HourClock(dtfi.ShortTimePattern);
Console.WriteLine("Modififed Property Values:");
Console.WriteLine("ShortTimePattern: " + dtfi.ShortTimePattern);
Console.WriteLine("LongTimePattern: " + dtfi.LongTimePattern);
Console.WriteLine("FullDateTimePattern: " + dtfi.FullDateTimePattern);
}
private static string ReplaceWith24HourClock(string fmt)
{
string pattern = @"^(?<openAMPM>\s*t+\s*)? " +
@"(?(openAMPM) h+(?<nonHours>[^ht]+)$ " +
@"| \s*h+(?<nonHours>[^ht]+)\s*t+)";
return Regex.Replace(fmt, pattern, "HH${nonHours}",
RegexOptions.IgnorePatternWhitespace);
}
}
// The example displays the following output:
// Original Property Values:
// ShortTimePattern: h:mm tt
// LongTimePattern: h:mm:ss tt
// FullDateTimePattern: dddd, MMMM dd, yyyy h:mm:ss tt
//
// Modififed Property Values:
// ShortTimePattern: HH:mm
// LongTimePattern: HH:mm:ss
// FullDateTimePattern: dddd, MMMM dd, yyyy HH:mm:ss
Imports System.Globalization
Imports System.Text.RegularExpressions
Module Example
Public Sub Main()
Dim enUS As CultureInfo = CultureInfo.CreateSpecificCulture("en-US")
Dim dtfi As DateTimeFormatInfo = enUS.DateTimeFormat
Console.WriteLine("Original Property Values:")
Console.WriteLine("ShortTimePattern: " + dtfi.ShortTimePattern)
Console.WriteLine("LongTimePattern: " + dtfi.LongTimePattern)
Console.WriteLine("FullDateTimePattern: " + dtfi.FullDateTimePattern)
Console.WriteLine()
dtfi.LongTimePattern = ReplaceWith24HourClock(dtfi.LongTimePattern)
dtfi.ShortTimePattern = ReplaceWith24HourClock(dtfi.ShortTimePattern)
Console.WriteLine("Modififed Property Values:")
Console.WriteLine("ShortTimePattern: " + dtfi.ShortTimePattern)
Console.WriteLine("LongTimePattern: " + dtfi.LongTimePattern)
Console.WriteLine("FullDateTimePattern: " + dtfi.FullDateTimePattern)
End Sub
Private Function ReplaceWith24HourClock(fmt As String) As String
Dim pattern As String = "^(?<openAMPM>\s*t+\s*)? " +
"(?(openAMPM) h+(?<nonHours>[^ht]+)$ " +
"| \s*h+(?<nonHours>[^ht]+)\s*t+)"
Return Regex.Replace(fmt, pattern, "HH${nonHours}", RegexOptions.IgnorePatternWhitespace)
End Function
End Module
' The example displays the following output:
' Original Property Values:
' ShortTimePattern: h:mm tt
' LongTimePattern: h:mm:ss tt
' FullDateTimePattern: dddd, MMMM dd, yyyy h:mm:ss tt
'
' Modififed Property Values:
' ShortTimePattern: HH:mm
' LongTimePattern: HH:mm:ss
' FullDateTimePattern: dddd, MMMM dd, yyyy HH:mm:ss
この例では、正規表現を使用して書式指定文字列を変更します。 正規表現パターン @"^(?<openAMPM>\s*t+\s*)? (?(openAMPM) h+(?<nonHours>[^ht]+)$ | \s*h+(?<nonHours>[^ht]+)\s*t+)
は次のように定義されます。
Pattern | 説明 |
---|---|
^ |
文字列の先頭から照合を開始します。 |
(?<openAMPM>\s*t+\s*)? |
0 個以上の空白文字が 0 個または 1 回出現し、その後に文字 "t" が 1 回以上続き、その後に 0 個以上の空白文字が続きます。 このキャプチャ グループの名前 openAMPM は です。 |
(?(openAMPM) h+(?<nonHours>[^ht]+)$ |
グループが openAMPM 一致する場合は、文字 "h" を 1 回以上一致し、その後に "h" と "t" のどちらでもない 1 つ以上の文字を一致させます。 一致は文字列の末尾で終了します。 "h" の後にキャプチャされたすべての文字は、 という名前 nonHours のキャプチャ グループに含まれます。 |
| \s*h+(?<nonHours>[^ht]+)\s*t+) |
グループが openAMPM 一致しない場合は、文字 "h" を 1 回以上一致し、その後に 1 つ以上の文字 ("h" または "t" ではない文字)、その後に 0 個以上の空白文字を指定します。 最後に、文字 "t" の出現箇所を 1 つ以上一致させます。 "h" の後と空白文字と "t" の前にキャプチャされたすべての文字は、 という名前 nonHours のキャプチャ グループに含まれます。 |
nonHours
キャプチャ グループには、時刻区切り記号と共に、カスタムの日付と時刻の書式指定文字列の分と場合によっては 2 番目のコンポーネントが含まれます。 置換パターン HH${nonHours}
は、これらの要素の前に部分文字列 "HH" を付加します。
日付の時代 (年号) の表示と変更
次の例では、"g" カスタム書式指定子を LongDatePattern 、en-US カルチャの書式設定規則を表す オブジェクトの プロパティに追加します。 この追加は、次の 3 つの標準書式指定文字列に影響します。
プロパティに直接 LongDatePattern マップされる "D" (長い日付) 標準書式指定文字列。
"f" (完全な日付/短い時刻) 標準書式指定文字列。これは、 プロパティと ShortTimePattern プロパティによって生成される部分文字列を連結する結果文字列をLongDatePattern生成します。
"F" (完全な日付/長い時間) の標準書式指定文字列。この文字列は、 プロパティに FullDateTimePattern 直接マップされます。 このプロパティ値は明示的に設定されていないため、 プロパティと LongTimePattern プロパティをLongDatePattern連結して動的に生成されます。
この例では、カレンダーに 1 つの年号があるカルチャの年号名を変更する方法も示します。 この場合、en-US カルチャでは、オブジェクトによって表されるグレゴリオ暦が GregorianCalendar 使用されます。 クラスは GregorianCalendar 、A.D. (Anno Domini) という名前の単一の時代 (年号) をサポートしています。 この例では、 プロパティに割り当てられた書式指定文字列の "g" カスタム書式指定子をリテラル文字列に置き換えることによって、時代 (年号) 名を C.E. (Common Era) に FullDateTimePattern 変更します。 年号名は通常、.NET Frameworkまたは Windows オペレーティング システムによって提供されるカルチャ テーブルのプライベート データから メソッドによってGetEraName返されるため、リテラル文字列を使用する必要があります。
using System;
using System.Globalization;
public class Example
{
public static void Main()
{
DateTime dateValue = new DateTime(2013, 5, 18, 13, 30, 0);
String[] formats = { "D", "f", "F" };
CultureInfo enUS = CultureInfo.CreateSpecificCulture("en-US");
DateTimeFormatInfo dtfi = enUS.DateTimeFormat;
String originalLongDatePattern = dtfi.LongDatePattern;
// Display the default form of three long date formats.
foreach (var fmt in formats)
Console.WriteLine(dateValue.ToString(fmt, dtfi));
Console.WriteLine();
// Modify the long date pattern.
dtfi.LongDatePattern = originalLongDatePattern + " g";
foreach (var fmt in formats)
Console.WriteLine(dateValue.ToString(fmt, dtfi));
Console.WriteLine();
// Change A.D. to C.E. (for Common Era)
dtfi.LongDatePattern = originalLongDatePattern + @" 'C.E.'";
foreach (var fmt in formats)
Console.WriteLine(dateValue.ToString(fmt, dtfi));
}
}
// The example displays the following output:
// Saturday, May 18, 2013
// Saturday, May 18, 2013 1:30 PM
// Saturday, May 18, 2013 1:30:00 PM
//
// Saturday, May 18, 2013 A.D.
// Saturday, May 18, 2013 A.D. 1:30 PM
// Saturday, May 18, 2013 A.D. 1:30:00 PM
//
// Saturday, May 18, 2013 C.E.
// Saturday, May 18, 2013 C.E. 1:30 PM
// Saturday, May 18, 2013 C.E. 1:30:00 PM
Imports System.Globalization
Module Example
Public Sub Main()
Dim dateValue As New Date(2013, 5, 18, 13, 30, 0)
Dim formats() As String = { "D", "f", "F" }
Dim enUS As CultureInfo = CultureInfo.CreateSpecificCulture("en-US")
Dim dtfi As DateTimeFormatInfo = enUS.DateTimeFormat
Dim originalLongDatePattern As String = dtfi.LongDatePattern
' Display the default form of three long date formats.
For Each fmt In formats
Console.WriteLine(dateValue.ToString(fmt, dtfi))
Next
Console.WriteLine()
' Modify the long date pattern.
dtfi.LongDatePattern = originalLongDatePattern + " g"
For Each fmt In formats
Console.WriteLine(dateValue.ToString(fmt, dtfi))
Next
Console.WriteLine()
' Change A.D. to C.E. (for Common Era)
dtfi.LongDatePattern = originalLongDatePattern + " 'C.E.'"
For Each fmt In formats
Console.WriteLine(dateValue.ToString(fmt, dtfi))
Next
End Sub
End Module
' The example displays the following output:
' Saturday, May 18, 2013
' Saturday, May 18, 2013 1:30 PM
' Saturday, May 18, 2013 1:30:00 PM
'
' Saturday, May 18, 2013 A.D.
' Saturday, May 18, 2013 A.D. 1:30 PM
' Saturday, May 18, 2013 A.D. 1:30:00 PM
'
' Saturday, May 18, 2013 C.E.
' Saturday, May 18, 2013 C.E. 1:30 PM
' Saturday, May 18, 2013 C.E. 1:30:00 PM
日付と時刻文字列の解析
解析では、日付と時刻の文字列形式を または DateTimeOffset 値に変換しますDateTime。 これらの型には、解析操作を Parse
サポートする 、 TryParse
、 ParseExact
、 TryParseExact
メソッドが含まれます。 メソッドと TryParse
メソッドはParse
、さまざまな形式を持つ文字列を変換しますがParseExact
TryParseExact
、文字列の書式または書式が定義されている必要があります。 解析操作が失敗し、Parse
例外がスローされた場合は をTryParse
返します。false
TryParseExact
ParseExact
解析メソッドは、列挙値を DateTimeStyles 暗黙的または明示的に使用して、解析する文字列内に存在できるスタイル要素 (先頭、末尾、内側の空白など) と、解析された文字列または不足している要素を解釈する方法を決定します。 または TryParse
メソッドを呼び出Parse
すときに値をDateTimeStyles指定しない場合、既定値は DateTimeStyles.AllowWhiteSpacesです。これは、および DateTimeStyles.AllowInnerWhite フラグをDateTimeStyles.AllowLeadingWhiteDateTimeStyles.AllowTrailingWhite含む複合スタイルです。 ParseExact
メソッドと TryParseExact
メソッドの場合、既定値は です。入力文字列はDateTimeStyles.None、特定のカスタム日時書式指定文字列に正確に対応している必要があります。
また、解析メソッドは、解析対象の文字列内で発生する可能性のある特定のシンボルとパターンを定義する オブジェクトを暗黙的または明示的に使用 DateTimeFormatInfo します。 オブジェクトを DateTimeFormatInfo 指定しない場合、現在のカルチャの DateTimeFormatInfo オブジェクトが既定で使用されます。 日付と時刻の文字列の解析の詳細については、、 などのDateTime.ParseDateTime.TryParseDateTimeOffset.ParseExactDateTimeOffset.TryParseExact個々の解析メソッドを参照してください。
次の例は、日付と時刻の文字列を解析するカルチャに依存する性質を示しています。 en-US、en-GB、fr-FR、および fi-FI カルチャの規則を使用して、2 つの日付文字列を解析しようとします。 en-US カルチャで 2014 年 8 月 18 日と解釈される日付は、18 が月番号として解釈されるため、他の 3 つのカルチャでは例外をスロー FormatException します。 2015 年 1 月 2 日は、en-US カルチャでは最初の月の 2 日目として解析されますが、残りのカルチャでは 2 か月目の最初の日として解析されます。
using System;
using System.Globalization;
public class Example
{
public static void Main()
{
string[] dateStrings = { "08/18/2014", "01/02/2015" };
string[] cultureNames = { "en-US", "en-GB", "fr-FR", "fi-FI" };
foreach (var cultureName in cultureNames) {
CultureInfo culture = CultureInfo.CreateSpecificCulture(cultureName);
Console.WriteLine("Parsing strings using the {0} culture.",
culture.Name);
foreach (var dateStr in dateStrings) {
try {
Console.WriteLine(String.Format(culture,
" '{0}' --> {1:D}", dateStr,
DateTime.Parse(dateStr, culture)));
}
catch (FormatException) {
Console.WriteLine(" Unable to parse '{0}'", dateStr);
}
}
}
}
}
// The example displays the following output:
// Parsing strings using the en-US culture.
// '08/18/2014' --> Monday, August 18, 2014
// '01/02/2015' --> Friday, January 02, 2015
// Parsing strings using the en-GB culture.
// Unable to parse '08/18/2014'
// '01/02/2015' --> 01 February 2015
// Parsing strings using the fr-FR culture.
// Unable to parse '08/18/2014'
// '01/02/2015' --> dimanche 1 février 2015
// Parsing strings using the fi-FI culture.
// Unable to parse '08/18/2014'
// '01/02/2015' --> 1. helmikuuta 2015
Imports System.Globalization
Module Example
Public Sub Main()
Dim dateStrings() As String = { "08/18/2014", "01/02/2015" }
Dim cultureNames() As String = { "en-US", "en-GB", "fr-FR", "fi-FI" }
For Each cultureName In cultureNames
Dim culture As CultureInfo = CultureInfo.CreateSpecificCulture(cultureName)
Console.WriteLine("Parsing strings using the {0} culture.",
culture.Name)
For Each dateStr In dateStrings
Try
Console.WriteLine(String.Format(culture,
" '{0}' --> {1:D}", dateStr,
DateTime.Parse(dateStr, culture)))
Catch e As FormatException
Console.WriteLine(" Unable to parse '{0}'", dateStr)
End Try
Next
Next
End Sub
End Module
' The example displays the following output:
' Parsing strings using the en-US culture.
' '08/18/2014' --> Monday, August 18, 2014
' '01/02/2015' --> Friday, January 02, 2015
' Parsing strings using the en-GB culture.
' Unable to parse '08/18/2014'
' '01/02/2015' --> 01 February 2015
' Parsing strings using the fr-FR culture.
' Unable to parse '08/18/2014'
' '01/02/2015' --> dimanche 1 février 2015
' Parsing strings using the fi-FI culture.
' Unable to parse '08/18/2014'
' '01/02/2015' --> 1. helmikuuta 2015
日付と時刻の文字列は、通常、次の 2 つの理由で解析されます。
ユーザー入力を日付と時刻の値に変換します。
日付と時刻の値をラウンドトリップするには、つまり、以前に文字列としてシリアル化された日付と時刻の値を逆シリアル化します。
次のセクションでは、これら 2 つの操作について詳しく説明します。
ユーザー文字列の解析
ユーザーが入力した日付と時刻の文字列を解析するときは、ユーザーが行った可能性のあるカスタマイズを含め、ユーザーのカルチャ設定を反映するオブジェクトを常にインスタンス化 DateTimeFormatInfo する必要があります。 それ以外の場合、日付と時刻のオブジェクトの値が正しくない可能性があります。 ユーザーカルチャのカスタマイズを反映するオブジェクトを DateTimeFormatInfo インスタンス化する方法については、「 DateTimeFormatInfo と動的データ 」セクションを参照してください。
次の例は、ユーザーカルチャ設定を反映する解析操作と反映されない操作の違いを示しています。 この場合、既定のシステム カルチャは en-US ですが、ユーザーは短い日付パターンを既定の "M/d/yyyy" から "yy/MM/dd" に変更するために、コントロール パネル、地域、言語を使用しています。 ユーザーがユーザー設定を反映する文字列を入力し、ユーザー設定も反映するオブジェクトによって DateTimeFormatInfo 文字列が解析されると (オーバーライド)、解析操作は正しい結果を返します。 ただし、文字列が標準の en-US カルチャ設定を反映するオブジェクトによって DateTimeFormatInfo 解析されると、解析メソッドは 14 を年の最後の 2 桁ではなく月の数として解釈するため、例外をスロー FormatException します。
using System;
using System.Globalization;
public class Example
{
public static void Main()
{
string inputDate = "14/05/10";
CultureInfo[] cultures = { CultureInfo.GetCultureInfo("en-US"),
CultureInfo.CreateSpecificCulture("en-US") };
foreach (var culture in cultures) {
try {
Console.WriteLine("{0} culture reflects user overrides: {1}",
culture.Name, culture.UseUserOverride);
DateTime occasion = DateTime.Parse(inputDate, culture);
Console.WriteLine("'{0}' --> {1}", inputDate,
occasion.ToString("D", CultureInfo.InvariantCulture));
}
catch (FormatException) {
Console.WriteLine("Unable to parse '{0}'", inputDate);
}
Console.WriteLine();
}
}
}
// The example displays the following output:
// en-US culture reflects user overrides: False
// Unable to parse '14/05/10'
//
// en-US culture reflects user overrides: True
// '14/05/10' --> Saturday, 10 May 2014
Imports System.Globalization
Module Example
Public Sub Main()
Dim inputDate As String = "14/05/10"
Dim cultures() As CultureInfo = { CultureInfo.GetCultureInfo("en-US"),
CultureInfo.CreateSpecificCulture("en-US") }
For Each culture In cultures
Try
Console.WriteLine("{0} culture reflects user overrides: {1}",
culture.Name, culture.UseUserOverride)
Dim occasion As DateTime = DateTime.Parse(inputDate, culture)
Console.WriteLine("'{0}' --> {1}", inputDate,
occasion.ToString("D", CultureInfo.InvariantCulture))
Catch e As FormatException
Console.WriteLine("Unable to parse '{0}'", inputDate)
End Try
Console.WriteLine()
Next
End Sub
End Module
' The example displays the following output:
' en-US culture reflects user overrides: False
' Unable to parse '14/05/10'
'
' en-US culture reflects user overrides: True
' '14/05/10' --> Saturday, 10 May 2014
日付と時刻のデータのシリアル化と逆シリアル化
シリアル化された日付と時刻のデータはラウンドトリップする必要があります。つまり、シリアル化された値と逆シリアル化された値はすべて同じである必要があります。 日付と時刻の値が 1 つの時点を表す場合、逆シリアル化された値は、復元されたシステムのカルチャまたはタイム ゾーンに関係なく、同じ瞬間を表す必要があります。 日付と時刻のデータをラウンドトリップするには、 プロパティによって InvariantInfo 返されるインバリアント カルチャの規則を使用して、データを生成して解析する必要があります。 書式設定と解析の操作では、既定のカルチャの規則を反映しないでください。 既定のカルチャ設定を使用する場合、データの移植性は厳密に制限されます。カルチャ固有の設定がシリアル化されたスレッドと同じスレッドでのみ、正常に逆シリアル化できます。 場合によっては、同じシステムでデータを正常にシリアル化および逆シリアル化できない場合もあります。
日付と時刻の値の時刻コンポーネントが重要な場合は、UTC に変換し、"o" または "r" 標準書式指定文字列を使用してシリアル化する必要もあります。 時間データを復元するには、解析メソッドを呼び出し、それをインバリアント カルチャと共に適切な書式指定文字列を provider
引数として渡します。
次の例は、日付と時刻の値をラウンドトリップするプロセスを示しています。 米国太平洋時間を観測し、現在のカルチャが en-US であるシステムで日付と時刻をシリアル化します。
using System;
using System.Globalization;
using System.IO;
public class Example
{
public static void Main()
{
StreamWriter sw = new StreamWriter(@".\DateData.dat");
// Define a date and time to serialize.
DateTime originalDate = new DateTime(2014, 08, 18, 08, 16, 35);
// Display information on the date and time.
Console.WriteLine("Date to serialize: {0:F}", originalDate);
Console.WriteLine("Current Culture: {0}",
CultureInfo.CurrentCulture.Name);
Console.WriteLine("Time Zone: {0}",
TimeZoneInfo.Local.DisplayName);
// Convert the date value to UTC.
DateTime utcDate = originalDate.ToUniversalTime();
// Serialize the UTC value.
sw.Write(utcDate.ToString("o", DateTimeFormatInfo.InvariantInfo));
sw.Close();
}
}
// The example displays the following output:
// Date to serialize: Monday, August 18, 2014 8:16:35 AM
// Current Culture: en-US
// Time Zone: (UTC-08:00) Pacific Time (US & Canada)
Imports System.Globalization
Imports System.IO
Module Example
Public Sub Main()
Dim sw As New StreamWriter(".\DateData.dat")
' Define a date and time to serialize.
Dim originalDate As New Date(2014, 08, 18, 08, 16, 35)
' Display information on the date and time.
Console.WriteLine("Date to serialize: {0:F}", originalDate)
Console.WriteLine("Current Culture: {0}",
CultureInfo.CurrentCulture.Name)
Console.WriteLine("Time Zone: {0}",
TimeZoneInfo.Local.DisplayName)
' Convert the date value to UTC.
Dim utcDate As Date = originalDate.ToUniversalTime()
' Serialize the UTC value.
sw.Write(utcDate.ToString("o", DateTimeFormatInfo.InvariantInfo))
sw.Close()
End Sub
End Module
' The example displays the following output:
' Date to serialize: Monday, August 18, 2014 8:16:35 AM
' Current Culture: en-US
' Time Zone: (UTC-08:00) Pacific Time (US & Canada)
ブリュッセル、コペンハーゲン、マドリード、パリのタイム ゾーンで、現在のカルチャが fr-FR であるシステム上のデータを逆シリアル化します。 復元日は元の日付より 9 時間遅れています。これは、UTC より 8 時間遅れてから UTC より 1 時間早いタイム ゾーン調整を反映しています。 元の日付と復元された日付の両方が、同じ時点を表します。
using System;
using System.Globalization;
using System.IO;
public class Example
{
public static void Main()
{
// Open the file and retrieve the date string.
StreamReader sr = new StreamReader(@".\DateData.dat");
String dateValue = sr.ReadToEnd();
// Parse the date.
DateTime parsedDate = DateTime.ParseExact(dateValue, "o",
DateTimeFormatInfo.InvariantInfo);
// Convert it to local time.
DateTime restoredDate = parsedDate.ToLocalTime();
// Display information on the date and time.
Console.WriteLine("Deserialized date: {0:F}", restoredDate);
Console.WriteLine("Current Culture: {0}",
CultureInfo.CurrentCulture.Name);
Console.WriteLine("Time Zone: {0}",
TimeZoneInfo.Local.DisplayName);
}
}
// The example displays the following output:
// Deserialized date: lundi 18 août 2014 17:16:35
// Current Culture: fr-FR
// Time Zone: (UTC+01:00) Brussels, Copenhagen, Madrid, Paris
Imports System.Globalization
Imports System.IO
Module Example
Public Sub Main()
' Open the file and retrieve the date string.
Dim sr As New StreamReader(".\DateData.dat")
Dim dateValue As String = sr.ReadToEnd()
' Parse the date.
Dim parsedDate As Date = Date.ParseExact(dateValue, "o",
DateTimeFormatInfo.InvariantInfo)
' Convert it to local time.
Dim restoredDate As Date = parsedDate.ToLocalTime()
' Display information on the date and time.
Console.WriteLine("Deserialized date: {0:F}", restoredDate)
Console.WriteLine("Current Culture: {0}",
CultureInfo.CurrentCulture.Name)
Console.WriteLine("Time Zone: {0}",
TimeZoneInfo.Local.DisplayName)
End Sub
End Module
' The example displays the following output:
' Deserialized date: lundi 18 août 2014 17:16:35
' Current Culture: fr-FR
' Time Zone: (UTC+01:00) Brussels, Copenhagen, Madrid, Paris
コンストラクター
DateTimeFormatInfo() |
カルチャに依存しない (インバリアントな) DateTimeFormatInfo クラスの新しい書き込み可能インスタンスを初期化します。 |
プロパティ
AbbreviatedDayNames |
曜日を表すカルチャ固有の省略名を格納している型 String の 1 次元配列を取得または設定します。 |
AbbreviatedMonthGenitiveNames |
現在の DateTimeFormatInfo オブジェクトに関連付けられた月の省略名の文字列配列を取得または設定します。 |
AbbreviatedMonthNames |
月を表すカルチャ固有の省略名を格納している 1 次元配列を取得または設定します。 |
AMDesignator |
"ante meridiem" (午前) の時間の文字列指定子を取得または設定します。 |
Calendar |
現在のカルチャで使用する暦を取得または設定します。 |
CalendarWeekRule |
年の最初の週を判断するために使用する規則を指定する値を取得または設定します。 |
CurrentInfo |
現在のカルチャに基づいて値を形式指定する読み取り専用 DateTimeFormatInfo オブジェクトを取得します。 |
DateSeparator |
日付の構成要素、つまり年、月、および日を区切る文字列を取得または設定します。 |
DayNames |
曜日を表すカルチャ固有の完全名を格納する 1 次元の文字列配列を取得または設定します。 |
FirstDayOfWeek |
週の最初の曜日を取得または設定します。 |
FullDateTimePattern |
長い日付値と長い時刻値のカスタム書式指定文字列を取得または設定します。 |
InvariantInfo |
カルチャに依存しない (インバリアントな) 既定の読み取り専用 DateTimeFormatInfo を取得します。 |
IsReadOnly |
DateTimeFormatInfo オブジェクトが読み取り専用かどうかを示す値を取得します。 |
LongDatePattern |
長い日付値のカスタム書式指定文字列を取得または設定します。 |
LongTimePattern |
長い時刻値のカスタム書式指定文字列を取得または設定します。 |
MonthDayPattern |
月と日の値のカスタム書式指定文字列を取得または設定します。 |
MonthGenitiveNames |
現在の DateTimeFormatInfo オブジェクトに関連付けられた月名の文字列配列を取得または設定します。 |
MonthNames |
月を表すカルチャ固有の完全名を格納している型 String の 1 次元配列を取得または設定します。 |
NativeCalendarName |
現在の DateTimeFormatInfo オブジェクトに関連付けられた暦のネイティブ名を取得します。 |
PMDesignator |
"post meridiem" (午後) の時間の文字列指定子を取得または設定します。 |
RFC1123Pattern |
インターネット技術標準化委員会の (IETF) の Request for Comments (RFC) 1123 仕様に基づく時刻値のカスタム書式指定文字列を取得します。 |
ShortDatePattern |
短い日付値のカスタム書式指定文字列を取得または設定します。 |
ShortestDayNames |
現在の DateTimeFormatInfo オブジェクトに関連付けられた曜日の最も短い一意の省略名の文字列配列を取得または設定します。 |
ShortTimePattern |
短い時刻値のカスタム書式指定文字列を取得または設定します。 |
SortableDateTimePattern |
並べ替え可能な日付と時刻の値のカスタム書式指定文字列を取得します。 |
TimeSeparator |
時刻の構成要素、つまり時間、分、および秒を区切る文字列を取得または設定します。 |
UniversalSortableDateTimePattern |
ISO 8601 での定義に従って、ユニバーサルで並べ替え可能な日付と時刻の文字列のカスタム書式指定文字列を取得します。 |
YearMonthPattern |
年と月の値のカスタム書式指定文字列を取得または設定します。 |
メソッド
Clone() |
DateTimeFormatInfo の簡易コピーを作成します。 |
Equals(Object) |
指定されたオブジェクトが現在のオブジェクトと等しいかどうかを判断します。 (継承元 Object) |
GetAbbreviatedDayName(DayOfWeek) |
現在の DateTimeFormatInfo オブジェクトに関連付けられたカルチャに基づいて、指定した曜日のカルチャ固有の省略名を返します。 |
GetAbbreviatedEraName(Int32) |
省略形が存在する場合は、指定した時代 (年号) の省略名を格納している文字列を返します。 |
GetAbbreviatedMonthName(Int32) |
現在の DateTimeFormatInfo オブジェクトに関連付けられたカルチャに基づいて、指定した月のカルチャ固有の省略名を返します。 |
GetAllDateTimePatterns() |
日付と時刻の値を形式指定できるすべての標準パターンを返します。 |
GetAllDateTimePatterns(Char) |
指定された標準書式指定文字列を使用して日付と時刻の値を形式指定できるすべてのパターンを返します。 |
GetDayName(DayOfWeek) |
現在の DateTimeFormatInfo オブジェクトに関連付けられたカルチャに基づいて、指定した曜日のカルチャ固有の完全名を返します。 |
GetEra(String) |
指定した時代 (年号) を表す整数を返します。 |
GetEraName(Int32) |
指定した時代 (年号) の名前を格納している文字列を返します。 |
GetFormat(Type) |
日付と時刻の書式設定サービスを提供する、指定した型のオブジェクトを返します。 |
GetHashCode() |
既定のハッシュ関数として機能します。 (継承元 Object) |
GetInstance(IFormatProvider) |
指定した DateTimeFormatInfo に関連付けられている IFormatProvider オブジェクトを返します。 |
GetMonthName(Int32) |
現在の DateTimeFormatInfo オブジェクトに関連付けられたカルチャに基づいて、指定した月のカルチャ固有の完全名を返します。 |
GetShortestDayName(DayOfWeek) |
現在の DateTimeFormatInfo オブジェクトに関連付けられた、指定した曜日の最も短い省略名を取得します。 |
GetType() |
現在のインスタンスの Type を取得します。 (継承元 Object) |
MemberwiseClone() |
現在の Object の簡易コピーを作成します。 (継承元 Object) |
ReadOnly(DateTimeFormatInfo) |
読み取り専用 DateTimeFormatInfo ラッパーを返します。 |
SetAllDateTimePatterns(String[], Char) |
指定された標準書式指定文字列に対応する、カスタムの日付と時刻の書式指定文字列を設定します。 |
ToString() |
現在のオブジェクトを表す文字列を返します。 (継承元 Object) |
明示的なインターフェイスの実装
ISerializable.GetObjectData(SerializationInfo, StreamingContext) |
SerializationInfo に、対象オブジェクトをシリアル化するために必要なデータを設定します。 |