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 物件是讀取/寫入。
DateTimeFormat從屬性傳回的物件中,抓取屬性的值 CultureInfo 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-us 則是特定的文化特性,代表加拿大所說的英文語言。 您可以利用下列方式具現化 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 物件
中立文化特性代表與國家/地區無關的文化特性或語言;它通常是一或多個特定文化特性的父系。 例如,Fr 是法文語言的中性文化特性,以及 fr-fr 文化特性的父系。 您可以具現化 DateTimeFormatInfo 物件,該物件表示中性文化特性的格式化慣例,其方式與建立 DateTimeFormatInfo 代表特定文化特性之格式慣例之物件的方式相同。 此外,您可以 DateTimeFormatInfo 從特定文化特性的屬性中抓取中性文化 CultureInfo.Parent 特性,並取得 DateTimeFormatInfo 其屬性傳回的物件,以抓取中性文化特性的物件 CultureInfo.DateTimeFormat 。 除非父文化特性代表不因文化特性而異,否則傳回的 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
注意
在 .NET Framework 1.0 至 .NET Framework 3.5 版中,嘗試取出 DateTimeFormatInfo 反映中性文化特性之格式慣例的物件會擲回例外狀況 NotSupportedException 。
不過,中立文化缺乏特定文化特性的格式資訊,因為它與特定的國家/地區無關。 DateTimeFormatInfo.NET Framework DateTimeFormatInfo 會傳回物件,以反映屬於中性文化特性之子系的特定文化特性的格式慣例,而不是使用泛型值來擴展物件。 例如,中立文化特性的 DateTimeFormatInfo 物件會反映 en-us 文化特性的格式化慣例,而 fr 文化特性的物件會 DateTimeFormatInfo 反映 fr-fr 文化特性的格式化慣例。
您可以使用類似下列的程式碼,來判斷中性文化特性所代表的特定文化特性格式慣例。 此範例會使用反映,將 DateTimeFormatInfo 中性文化特性的屬性與特定子文化特性的屬性進行比較。 它會將兩個行事曆視為相同的行事曆類型,如果是西曆,則會將其視為相同的行事曆,如果他們的 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 物件是唯讀的。
DateTimeFormat從屬性傳回的物件中,抓取屬性的值 CultureInfo 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 下列其中一種方式建立可寫入物件,以代表目前文化特性的慣例:
藉由使用 DateTimeFormatInfo 上述任何一種方式來抓取物件,並在 Clone 傳回的物件上呼叫方法 DateTimeFormatInfo 。 這會建立原始物件的複本 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 中,使用者可以 DateTimeFormatInfo 透過主控台的 區域和語言 應用程式,覆寫一些用於格式化和剖析作業的屬性值。 例如,如果使用者的文化特性是英文 (美國) 可能會選擇使用24小時制來顯示長時間值 (格式為 HH: mm: ss) ,而不是預設的12小時時鐘 (格式為 h:mm: ss tt) 。 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 。 對於 DateTimeFormatInfo 與特定物件相關聯的物件,您不應該對其值的穩定性做出任何假設 CultureInfo 。 只有不因文化特性而異的資料與其相關聯的 DateTimeFormatInfo 物件是穩定的。 其他資料可能會在應用程式會話之間變更,甚至是在您的應用程式執行時變更。 有四個主要的變更來源:
系統更新。 文化喜好設定(例如偏好行事曆或慣例日期和時間格式)會隨時間而改變。 發生這種情況時,Windows Update 包含 DateTimeFormatInfo 特定文化特性的屬性值變更。
取代文化特性。 CultureAndRegionInfoBuilder類別可以用來取代現有文化特性的資料。
對屬性值進行級聯的變更。 許多與文化特性相關的屬性可能會在執行時間變更,因而導致 DateTimeFormatInfo 資料變更。 例如,您可以透過程式設計方式或透過使用者動作來變更目前的文化特性。 發生這種情況時, DateTimeFormatInfo 屬性傳回的物件會 CurrentInfo 變更為與目前文化特性相關聯的物件。 同樣地,文化特性的行事曆也可以變更,這可能會導致許多 DateTimeFormatInfo 屬性值的變更。
使用者喜好設定。 您應用程式的使用者可以選擇透過主控台中的 [地區和語言] 選項,覆寫與目前系統文化特性相關聯的一些值。 例如,使用者可能會選擇以不同的格式來顯示日期。 如果 CultureInfo.UseUserOverride 屬性設定為,則
true
DateTimeFormatInfo 也會從使用者設定中取出物件的屬性。 如果使用者設定與物件相關聯的文化特性不相容 CultureInfo (例如,如果選取的行事曆不是屬性) 所指出的其中一個行事曆 OptionalCalendars ,則方法的結果和屬性的值都是未定義的。
為了將不一致資料的可能性降至最低, 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在所有日期和時間格式化作業中,隱含或明確使用物件。 這些包括呼叫下列方法:
所有日期和時間格式化方法,例如 DateTime.ToString() 和 DateTimeOffset.ToString(String) 。
主要的複合格式方法,也就是 String.Format 。
其他複合格式化方法,例如 Console.WriteLine(String, Object[]) 和 StringBuilder.AppendFormat(String, Object[]) 。
所有日期和時間格式化作業都會使用實作為 IFormatProvider 。 IFormatProvider介面包含單一方法 IFormatProvider.GetFormat(Type) 。 此回呼方法會傳遞 Type 代表提供格式資訊所需之類型的物件。 方法會傳回該類型的實例,或者, null
如果它無法提供類型的實例,則為。 .NET Framework 包含兩種 IFormatProvider 格式化日期和時間的實作為:
CultureInfo類別,表示特定文化特性 (或特定國家/地區) 中的特定語言。 在日期和時間格式化作業中,方法會傳回與其 CultureInfo.GetFormat DateTimeFormatInfo 屬性相關聯的物件 CultureInfo.DateTimeFormat 。
DateTimeFormatInfo類別,提供與其相關聯文化特性之格式設定慣例的相關資訊。 方法會傳回 DateTimeFormatInfo.GetFormat 本身的實例。
如果 IFormatProvider 未明確提供實作為格式化方法的執行,則 CultureInfo CultureInfo.CurrentCulture 會使用代表目前文化特性的屬性所傳回的物件。
下列範例說明在 IFormatProvider 格式化作業中,介面和類別之間的關聯性 DateTimeFormatInfo 。 它會定義自訂 IFormatProvider 執行,其 GetFormat 方法會顯示格式化作業所要求之物件的類型。 如果要求 DateTimeFormatInfo 物件,方法會提供目前文化特性的 DateTimeFormatInfo 物件。 如範例的輸出所示,方法會 Decimal.ToString(IFormatProvider) 要求 DateTimeFormatInfo 物件來提供格式設定資訊,而方法會 String.Format(IFormatProvider, String, Object[]) 要求 NumberFormatInfo 和物件,以及 DateTimeFormatInfo ICustomFormatter 執行。
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 物件包含三種屬性,用於格式化具有日期和時間值的作業:
行事曆相關的屬性。 屬性(例如 AbbreviatedDayNames 、 AbbreviatedMonthNames 、 DayNames 和 MonthNames )會與文化特性所使用的行事曆相關聯,這是由屬性所定義 Calendar 。 這些屬性會用於完整的日期和時間格式。
產生標準定義結果字串的屬性。 RFC1123Pattern、 SortableDateTimePattern 和 UniversalSortableDateTimePattern 屬性包含自訂格式字串,這些字串會產生由國際標準所定義的結果字串。 這些屬性是唯讀的,而且無法修改。
定義區分文化特性之結果字串的屬性。 某些屬性(例如 FullDateTimePattern 和 ShortDatePattern )包含可指定結果字串格式的 自訂格式字串 。 其他(例如 AMDesignator 、 DateSeparator 、 PMDesignator 和 TimeSeparator )會定義區分文化特性的符號或可包含在結果字串中的子字串。
標準日期和時間格式字串(例如 "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" (month/day;標準格式字串) | MonthDayPattern,用以定義結果字串的整體格式。 |
"O"、"o" (來回日期/時間;標準格式字串) | 無。 |
"R"、"r" (RFC1123;標準格式字串) | RFC1123Pattern,定義符合 RFC 1123 標準的結果字串。 此為唯讀屬性。 |
"s" (可排序日期/時間;標準格式字串) | SortableDateTimePattern,定義符合 ISO 8601 標準的結果字串。 此為唯讀屬性。 |
"t" (短時間;標準格式字串) | ShortTimePattern,用以定義結果字串的整體格式。 |
"T" (長時間;標準格式字串) | LongTimePattern,用以定義結果字串的整體格式。 |
"u" (通用可排序日期/時間;標準格式字串) | UniversalSortableDateTimePattern,定義符合國際標準時間 ISO 8601 標準的結果字串。 此為唯讀屬性。 |
"U" (通用的完整日期/時間;標準格式字串) | FullDateTimePattern,用以定義結果字串的整體格式。 |
"Y"、"y" (year month;標準格式字串) | 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 屬性。 )
DateTimeFormatInfo在對格式化方法的呼叫中,使用您建立的自訂物件做為自 IFormatProvider 變數。
有兩種方式可以變更結果字串的格式:
您可以使用 CultureAndRegionInfoBuilder 類別來定義自訂文化特性 (具有唯一名稱的文化特性,以及補充現有文化特性) 或取代文化特性 (使用的文化特性,而不是) 的特定文化特性。 您可以用程式設計方式儲存和存取此文化特性,就像 .NET Framework 所支援的任何 CultureInfo 物件一樣。
如果結果字串不區分文化特性,且未遵循預先定義的格式,您可以使用自訂日期和時間格式字串。 例如,如果您要以 Yyyymmddhhmmss.ffffff 格式序列化日期和時間資料,您可以藉由將自訂格式字串傳遞給方法來產生結果字串,也 DateTime.ToString(String) 可以藉由呼叫方法將結果字串轉換回 DateTime 值 DateTime.ParseExact 。
變更簡短日期模式
下列範例會變更 "d" (簡短日期) 標準格式字串所產生的結果字串格式。 它會將 ShortDatePattern en-us 或英文 (美國) 文化特性的相關屬性,從其預設值 "M/d/yyyy" 變更為 "yyyy '-" 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
變更日期分隔字元
下列範例會變更物件中的日期分隔符號 DateTimeFormatInfo ,以表示 fr-fr 文化特性的格式化慣例。 此範例會使用 "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 文化特性的完整日期模式,以傳回一個字元或兩個字元的日名稱縮寫,後面接著 day、month name 縮寫和 year。 它會藉由將較短的日期名稱縮寫指派給 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
方法,此方法會以使用24小時制的格式來取代任何使用12小時制的時間格式。
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+)
定義如下:
模式 | 描述 |
---|---|
^ |
從字串的開頭開始比對。 |
(?<openAMPM>\s*t+\s*)? |
比對零或一次出現零或多個空白字元,後面接著字母 "t" 一或多次,後面接著零或多個空白字元。 此捕獲群組的名稱為 openAMPM 。 |
(?(openAMPM) h+(?<nonHours>[^ht]+)$ |
如果 openAMPM 群組有相符的字元,請比對字母 "h" 一或多次,後面接著一或多個非 "h" 或 "t" 的字元。 比對會結束于字串的結尾。 "H" 之後所捕捉的所有字元都會包含在名為的捕獲群組中 nonHours 。 |
| \s*h+(?<nonHours>[^ht]+)\s*t+) |
如果群組沒有相符的值 openAMPM ,請比對字母 "h" 一或多次,後面接著一或多個不是 "h" 或 "t" 的字元,後面接著零或多個空白字元。 最後,比對一或多個字母 "t" 的相符專案。 在 "h" 之後且在空白字元和 "t" 之前捕捉的所有字元,都會包含在名為的捕獲群組中 nonHours 。 |
此「 nonHours
捕獲群組」包含時間,以及自訂日期和時間格式字串的第二個元件,以及任何時間分隔符號符號。 取代模式會將 HH${nonHours}
子字串 "HH" 加到這些元素前面。
在日期中顯示和變更紀元
下列範例會將 "g" 自訂格式規範新增至 LongDatePattern 物件的屬性,該物件表示 en-us 文化特性的格式化慣例。 這項加法會影響下列三個標準格式字串:
"D" (完整日期) 標準格式字串,此字串會直接對應至 LongDatePattern 屬性。
"F" (完整日期/短時間) 標準格式字串,此字串會產生串連和屬性所產生之子字串的結果字串 LongDatePattern ShortTimePattern 。
"F" (完整日期/時間) 標準格式字串,此字串會直接對應至 FullDateTimePattern 屬性。 因為我們並未明確設定此屬性值,所以會串連和屬性以動態方式 LongDatePattern 產生 LongTimePattern 。
此範例也會示範如何變更行事曆具有單一紀元之文化特性的紀元名稱。 在此情況下,en-us 文化特性會使用西曆(以物件表示) GregorianCalendar 。 GregorianCalendar類別支援單一紀元,其名稱為西元 (西元西元) 。 此範例會將紀元名稱變更為西元 使用常值字串,將指派給屬性的格式字串中的 "g" 自訂格式規範取代為 (的一般紀元) FullDateTimePattern 。 使用常值字串是必要的,因為在 GetEraName .NET Framework 或 Windows 作業系統所提供的文化特性資料表中,方法通常會從私用資料傳回紀元名稱。
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
剖析日期和時間字串
剖析牽涉到將日期和時間的字串表示轉換為 DateTime 或 DateTimeOffset 值。 這兩種類型都包含 Parse
、 TryParse
、 ParseExact
和 TryParseExact
方法,以支援剖析作業。 Parse
和 TryParse
方法會轉換可以有各種格式的字串,而 ParseExact
TryParseExact
要求字串必須有定義的格式或格式。 如果剖析作業失敗, Parse
並 ParseExact
擲回例外狀況,則會擲回,而會傳回 TryParse
TryParseExact
false
。
剖析方法會隱含或明確地使用 DateTimeStyles 列舉值來判斷 (的樣式元素,例如前置、尾端或內部空白字元) 可出現在要剖析的字串中,以及如何解讀剖析的字串或任何遺漏的元素。 如果您在 DateTimeStyles 呼叫或方法時未提供值 Parse
TryParse
,則預設為 DateTimeStyles.AllowWhiteSpaces ,這是包含 DateTimeStyles.AllowLeadingWhite 、 DateTimeStyles.AllowTrailingWhite 和旗標的複合樣式 DateTimeStyles.AllowInnerWhite 。 針對 ParseExact
和 TryParseExact
方法,預設值為 DateTimeStyles.None ; 輸入字串必須精確對應至特定的自訂日期和時間格式字串。
剖析方法也會隱含或明確地使用 DateTimeFormatInfo 物件,該物件定義可在要剖析的字串中出現的特定符號和模式。 如果您未提供 DateTimeFormatInfo 物件, DateTimeFormatInfo 預設會使用目前文化特性的物件。 如需有關剖析日期和時間字串的詳細資訊,請參閱個別的剖析方法,例如 DateTime.Parse 、 DateTime.TryParse 、 DateTimeOffset.ParseExact 和 DateTimeOffset.TryParseExact 。
下列範例說明剖析日期和時間字串的區分文化特性本質。 它會嘗試使用 en-us、en-us、fr-fr 和 fi 文化特性的慣例來剖析兩個日期字串。 在 en-us 文化特性中解釋為8/18/2014 的日期會 FormatException 在其他三種文化特性中擲回例外狀況,因為18會被解釋為月份編號。 1/2/2015 會剖析為 en-us 文化特性中第一個月的第二天,但在其餘的文化特性中,是第二個月的第一天。
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
日期和時間字串的剖析通常有兩個原因:
將使用者輸入轉換成日期和時間值。
來回行程日期和時間值;也就是還原序列化先前序列化為字串的日期和時間值。
下列各節會更詳細地討論這兩項作業。
剖析使用者字串
當您剖析使用者輸入的日期和時間字串時,您應該一律將 DateTimeFormatInfo 反映使用者文化設定的物件具現化,包括使用者可能進行的任何自訂。 否則,日期和時間物件可能會有不正確的值。 如需如何具現化 DateTimeFormatInfo 反映使用者文化自訂之物件的相關資訊,請參閱 DateTimeFormatInfo 和動態資料 一節。
下列範例說明會反映使用者文化設定的剖析作業與不存在的使用者文化設定之間的差異。 在此情況下,預設系統文化特性是 en-us,但使用者已使用主控台、 地區和語言 ,將簡短日期模式從預設值 "M/d/yyyy" 變更為 "YY/MM/dd"。 當使用者輸入反映使用者設定的字串,且字串是由 DateTimeFormatInfo 也反映使用者設定 (覆寫) 的物件所剖析時,剖析作業會傳回正確的結果。 不過,當以 DateTimeFormatInfo 反映標準 en-us 文化特性設定的物件剖析字串時,剖析方法會擲回例外狀況, FormatException 因為它會將14視為月份的數目,而不是年份的最後兩個數字。
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
序列化和還原序列化日期和時間資料
序列化的日期和時間資料應該會往返;也就是說,所有序列化和還原序列化的值都應該相同。 如果日期和時間值代表一個時間點,則不論還原的系統文化特性或時區為何,還原序列化的值都應該代表相同的時間點。 若要成功地反復存取日期和時間資料,您必須使用屬性所傳回之不因文化特性而異的慣例 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 之後的八小時到 UTC 之前的一小時。 原始日期和還原日期都代表相同的時間點。
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)。 |
AbbreviatedMonthGenitiveNames |
取得或設定字串陣列,這個陣列包含與目前 DateTimeFormatInfo 物件關聯的縮寫月份名稱。 |
AbbreviatedMonthNames |
取得或設定包含特定文化特性之月份縮寫名稱的一維字串陣列。 |
AMDesignator |
取得或設定 "ante meridiem" (正午以前) 小時的字串指示項。 |
Calendar |
取得或設定目前文化特性所使用的曆法。 |
CalendarWeekRule |
取得或設定數值,指定要使用哪一個規則 (Rule) 來決定一年中的第一個日曆週。 |
CurrentInfo |
取得根據目前文化特性格式化值的唯讀 DateTimeFormatInfo 物件。 |
DateSeparator |
取得或設定分隔日期組成部分 (即年、月和日) 的字串。 |
DayNames |
取得或設定包含特定文化特性之一週日期完整名稱的一維字串陣列。 |
FirstDayOfWeek |
取得或設定一週的第一天。 |
FullDateTimePattern |
取得或設定完整日期和時間值的自訂格式字串。 |
InvariantInfo |
取得與文化特性無關 (非變異) 的預設唯讀 DateTimeFormatInfo 物件。 |
IsReadOnly |
取得值,這個值表示 DateTimeFormatInfo 物件是否唯讀。 |
LongDatePattern |
取得或設定完整日期值的自訂格式字串。 |
LongTimePattern |
取得或設定完整時間值的自訂格式字串。 |
MonthDayPattern |
取得或設定月份和日值的自訂格式字串。 |
MonthGenitiveNames |
取得或設定字串陣列,這個陣列包含與目前 DateTimeFormatInfo 物件關聯的月份名稱。 |
MonthNames |
取得或設定包含特定文化特性之月份完整名稱的一維陣列 (型別為 String)。 |
NativeCalendarName |
取得行事曆的原生 (Native) 名稱,這個行事曆與目前 DateTimeFormatInfo 物件關聯。 |
PMDesignator |
取得或設定 "post meridiem" (正午以後) 小時的字串指示項。 |
RFC1123Pattern |
取得時間值的自訂格式字串,這個字串是根據網際網路工程任務推動小組 (Internet Engineering Task Force,IETF) 要求建議 (RFC) 1123 規格。 |
ShortDatePattern |
取得或設定簡短日期值的自訂格式字串。 |
ShortestDayNames |
取得或設定字串陣列,這個陣列包含與目前 DateTimeFormatInfo 物件關聯的最短唯一縮寫日名稱。 |
ShortTimePattern |
取得或設定簡短時間值的自訂格式字串。 |
SortableDateTimePattern |
取得可排序日期和時間值的自訂格式字串。 |
TimeSeparator |
取得或設定分隔時間組成部分 (即時、分和秒) 的字串。 |
UniversalSortableDateTimePattern |
取得自訂格式字串,以取得由 ISO 8601 所定義的國際標準、可排序日期和時間字串。 |
YearMonthPattern |
取得或設定年份和月份值的自訂格式字串。 |
方法
明確介面實作
ISerializable.GetObjectData(SerializationInfo, StreamingContext) |
將序列化目標物件所需的資料填入 SerializationInfo 中。 |