DateTimeFormatInfo 클래스

이 문서에서는 이 API에 대한 참조 설명서에 대한 추가 설명서를 제공합니다.

클래스의 DateTimeFormatInfo 속성에는 다음과 같은 날짜 및 시간 값의 서식을 지정하거나 구문 분석하기 위한 문화권별 정보가 포함됩니다.

  • 날짜 값의 서식을 지정하는 데 사용되는 패턴입니다.
  • 시간 값의 서식을 지정하는 데 사용되는 패턴입니다.
  • 요일의 이름입니다.
  • 해당 연도의 월 이름입니다.
  • 시간 값에 사용되는 오전 및 오후 지정자입니다.
  • 날짜가 표현되는 달력입니다.

DateTimeFormatInfo 개체 인스턴스화

개체는 DateTimeFormatInfo 고정 문화권, 특정 문화권, 중립 문화권 또는 현재 문화권의 서식 규칙을 나타낼 수 있습니다. 이 섹션에서는 각 개체 형식 DateTimeFormatInfo 을 인스턴스화하는 방법을 설명합니다.

고정 문화권에 대한 DateTimeFormatInfo 개체 인스턴스화

고정 문화권은 문화권을 구분하지 않는 문화권을 나타냅니다. 그것은 영어에 따라, 하지만 어떤 특정 영어권 국가/지역에. 특정 문화권의 데이터는 동적일 수 있으며 새로운 문화권 규칙 또는 사용자 기본 설정을 반영하도록 변경할 수 있지만 고정 문화권의 데이터는 변경되지 않습니다. 다음과 같은 방법으로 고정 문화권의 서식 규칙을 나타내는 개체를 인스턴스화 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

특정 문화권에 대한 DateTimeFormatInfo 개체 인스턴스화

특정 문화권은 특정 국가/지역에서 사용되는 언어를 나타냅니다. 예를 들어 en-US는 미국 사용되는 영어를 나타내는 특정 문화권이며 en-CA는 캐나다에서 사용되는 영어를 나타내는 특정 문화권입니다. 다음과 같은 방법으로 특정 문화권의 서식 규칙을 나타내는 개체를 인스턴스화 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

중립 문화권에 대한 DateTimeFormatInfo 개체 인스턴스화

중립 문화권은 국가/지역과 독립적인 문화권 또는 언어를 나타냅니다. 일반적으로 하나 이상의 특정 문화권의 부모입니다. 예를 들어 Fr은 프랑스어와 fr-FR 문화권의 부모에 대한 중립 문화권입니다. 특정 문화권의 서식 규칙을 나타내는 개체를 만드는 DateTimeFormatInfo 것과 동일한 방식으로 중립 문화권의 서식 규칙을 나타내는 개체를 인스턴스화 DateTimeFormatInfo 할 수 있습니다. 또한 특정 문화권의 DateTimeFormatInfo 속성에서 중립 문화권을 검색하고 해당 속성에서 반환된 개체를 검색하여 중립 문화권 DateTimeFormatInfoCultureInfo.Parent 개체를 검색할 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

그러나 중립 문화권은 특정 국가/지역과 독립적이기 때문에 문화권별 서식 지정 정보가 부족합니다. .NET은 개체를 DateTimeFormatInfo 제네릭 값으로 채우는 대신 중립 문화권의 자식인 특정 문화권의 서식 규칙을 반영하는 개체를 반환 DateTimeFormatInfo 합니다. 예를 들어 DateTimeFormatInfo 중립 en 문화권의 개체는 en-US 문화권의 서식 규칙을 반영하고 DateTimeFormatInfo fr 문화권의 개체는 fr-FR 문화권의 서식 규칙을 반영합니다.

다음과 같은 코드를 사용하여 중립 문화권이 나타내는 특정 문화권의 서식 지정 규칙을 결정할 수 있습니다. 이 예제에서는 리플렉션을 사용하여 중립 문화권의 속성을 특정 자식 문화권의 속성과 비교 DateTimeFormatInfo 합니다. 두 달력이 동일한 달력 유형인 경우 동일한 것으로 간주하고, 양력의 경우 속성에 동일한 값이 있는 경우 GregorianCalendar.CalendarType 동일한 것으로 간주합니다.

using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.Reflection;

public class InstantiateEx6
{
    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();
    }
}

현재 문화권에 대한 DateTimeFormatInfo 개체 인스턴스화

다음과 같은 방법으로 현재 문화권의 서식 규칙을 나타내는 개체를 인스턴스화 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

다음 방법 중 하나로 현재 문화권의 규칙을 나타내는 쓰기 가능한 DateTimeFormatInfo 개체를 만들 수 있습니다.

다음 예제에서는 읽기/쓰기 DateTimeFormatInfo 개체를 인스턴스화하는 각 방법을 보여 줍니다. 해당 IsReadOnly 속성의 값을 표시합니다.

using System;
using System.Globalization;

public class InstantiateEx1
{
    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

에서는 Windows에서 사용자를 재정의할 수 중 일부는 DateTimeFormatInfo 서식 지정 및 구문 분석을 통해 작업에 사용 된 속성 값을 국가 및 언어 제어판 애플리케이션입니다. 예를 들어 문화권이 영어(미국)인 사용자는 기본 12시간 클록(h:mm:ss tt 형식) 대신 24시간 클록(HH:mm:ss 형식)을 사용하여 장시간 값을 표시하도록 선택할 수 있습니다. 앞에서 설명한 방식으로 검색된 개체는 DateTimeFormatInfo 모두 이러한 사용자 재정의를 반영합니다. 바람직하지 않은 경우 생성자를 호출 CultureInfo.CultureInfo(String, Boolean) 하고 인수에 대한 useUserOverride 값을 false 제공하여 사용자 재정의를 반영하지 않고 읽기 전용이 아닌 읽기/쓰기인 개체를 만들 NumberFormatInfo 수 있습니다. 다음 예제에서는 현재 문화권이 영어(미국)이고 긴 시간 패턴이 h:mm:ss tt의 기본값에서 HH:mm:ss로 변경된 시스템에 대해 이를 보여 줍니다.

using System;
using System.Globalization;

public class InstantiateEx3
{
    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

DateTimeFormatInfo 및 동적 데이터

클래스에서 제공하는 DateTimeFormatInfo 날짜 및 시간 값의 서식을 지정하기 위한 문화권별 데이터는 클래스에서 제공하는 CultureInfo 문화권 데이터와 마찬가지로 동적입니다. 특정 CultureInfo 개체와 연결된 개체에 대한 값의 안정성을 DateTimeFormatInfo 가정해서는 안 됩니다. 고정 문화권 및 관련 DateTimeFormatInfo 개체에서 제공하는 데이터만 안정적입니다. 다른 데이터는 애플리케이션 세션 간에 또는 애플리케이션을 실행 하는 동안에 변경할 수 있습니다. 다음과 같은 네 가지 주요 변경 요소가 있습니다.

  • 시스템 업데이트 기본 달력 또는 사용자 지정 날짜 및 시간 형식과 같은 문화권 기본 설정은 시간에 따라 변경됩니다. 이 경우 Windows 업데이트 특정 문화권의 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 개체는 모든 날짜 및 시간 서식 지정 작업에서 암시적 또는 명시적으로 사용됩니다. 여기에는 다음 메서드에 대한 호출이 포함됩니다.

모든 날짜 및 시간 서식 지정 작업은 구현을 IFormatProvider 사용합니다. 인터페이스에는 IFormatProvider 단일 메서드가 IFormatProvider.GetFormat(Type)포함됩니다. 이 콜백 메서드는 서식 정보를 제공하는 데 필요한 형식을 나타내는 개체로 전달 Type 됩니다. 메서드는 해당 형식의 인스턴스를 반환하거나 null 형식의 인스턴스를 제공할 수 없는 경우 반환합니다. .NET에는 날짜 및 시간을 서식 지정하기 위한 두 가지 IFormatProvider 구현이 포함되어 있습니다.

형식 지정 메서드에 IFormatProvider 구현이 명시적으로 CultureInfo 제공되지 않으면 현재 문화권을 나타내는 속성에서 CultureInfo.CurrentCulture 반환된 개체가 사용됩니다.

다음 예제에서는 형식 지정 작업에서 인터페이스와 DateTimeFormatInfo 클래스 간의 IFormatProvider 관계를 보여 줍니다. 서식 지정 작업에서 요청한 개체의 형식을 표시하는 사용자 지정 IFormatProvider 구현 GetFormat 을 정의합니다. 개체를 DateTimeFormatInfo 요청하는 경우 메서드는 현재 문화권에 DateTimeFormatInfo 대한 개체를 제공합니다. 예제의 출력에서 알 Decimal.ToString(IFormatProvider) 수 있듯이 메서드는 개체를 요청 DateTimeFormatInfo 하여 형식 지정 정보를 제공하는 반면 String.Format(IFormatProvider, String, Object[]) 메서드는 구현뿐만 아니라 요청 NumberFormatInfoDateTimeFormatInfo 개체를 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 FormatProviderEx1
{
    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

문자열 및 DateTimeFormatInfo 속성 서식 지정

이 개체에는 DateTimeFormatInfo 날짜 및 시간 값을 사용하여 서식 지정 작업에 사용되는 세 가지 종류의 속성이 포함됩니다.

표준 날짜 및 시간 형식 문자열(예: "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; 표준 형식 문자열) RFC1123Pattern- RFC 1123 표준을 준수하는 결과 문자열을 정의합니다. 속성이 읽기 전용입니다.
"s"(정렬 가능한 날짜/시간, 표준 형식 문자열) SortableDateTimePatternISO 8601 표준을 준수하는 결과 문자열을 정의합니다. 속성이 읽기 전용입니다.
"t"(짧은 시간, 표준 형식 문자열) ShortTimePattern- 결과 문자열의 전체 형식을 정의합니다.
"T"(long time; standard format string) 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 수행합니다.

  1. 서식 규칙을 수정하려는 개체의 DateTimeFormatInfo 읽기/쓰기 복사본을 만듭니다.

  2. 원하는 결과 문자열을 생성하는 데 사용되는 속성 또는 속성을 수정합니다. (서식 지정 메서드가 속성을 사용하여 DateTimeFormatInfo 결과 문자열을 정의하는 방법에 대한 자세한 내용은 이전 섹션인 형식 문자열 및 DateTimeFormatInfo 속성을 참조하세요.)

  3. 만든 사용자 지정 DateTimeFormatInfo 개체를 IFormatProvider 형식 지정 메서드 호출에서 인수로 사용합니다.

결과 문자열의 형식을 변경하는 다른 두 가지 방법이 있습니다.

  • 클래스를 CultureAndRegionInfoBuilder 사용하여 사용자 지정 문화권(고유한 이름을 가지며 기존 문화권을 보완하는 문화권) 또는 대체 문화권(특정 문화권 대신 사용되는 문화권)을 정의할 수 있습니다. .NET에서 지원하는 모든 CultureInfo 개체와 마찬가지로 프로그래밍 방식으로 이 문화권을 저장하고 액세스할 수 있습니다.

  • 결과 문자열이 문화권을 구분하지 않고 미리 정의된 형식을 따르지 않는 경우 사용자 지정 날짜 및 시간 형식 문자열을 사용할 수 있습니다. 예를 들어 날짜 및 시간 데이터를 YYYYMMDDHHmmss 형식으로 serialize하는 경우 사용자 지정 형식 문자열을 메서드에 전달하여 결과 문자열 DateTime.ToString(String) 을 생성할 수 있으며, 메서드를 호출 DateTime.ParseExact 하여 결과 문자열을 값으로 다시 변환할 DateTime 수 있습니다.

짧은 날짜 패턴 변경

다음 예제에서는 "d"(짧은 날짜) 표준 형식 문자열에 의해 생성된 결과 문자열의 형식을 변경합니다. en-US 또는 영어(미국) 문화권의 연결된 ShortDatePattern 속성을 기본값인 "M/d/yyyy"에서 "yyyy'-"MM"-"dd"로 변경하고 "d" 표준 형식 문자열을 사용하여 속성이 변경되기 전과 후에 ShortDatePattern 날짜를 표시합니다.

using System;
using System.Globalization;

public class Example1
{
    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

날짜 구분 기호 문자 변경

다음은 fr-FR 문화권의 서식 규칙을 나타내는 개체의 날짜 구분 기호 문자를 DateTimeFormatInfo 변경하는 예제입니다. 이 예제에서는 "g" 표준 형식 문자열을 사용하여 속성이 변경되기 전과 후에 DateSeparator 날짜를 표시합니다.

using System;
using System.Globalization;

public class Example3
{
    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

날짜 이름 약어 및 긴 날짜 패턴 변경

경우에 따라 일반적으로 전체 날짜 및 월 이름을 월 및 연도의 일 수와 함께 표시하는 긴 날짜 패턴이 너무 길 수 있습니다. 다음 예제에서는 en-US 문화권의 긴 날짜 패턴을 줄여 1자 또는 2자 일 이름 약어와 일 번호, 월 이름 약어 및 연도를 반환합니다. 이 작업은 배열에 더 짧은 일 이름 약어를 AbbreviatedDayNames 할당하고 속성에 할당된 LongDatePattern 사용자 지정 형식 문자열을 수정하여 수행합니다. 이는 "D" 및 "f" 표준 형식 문자열에서 반환된 결과 문자열에 영향을 줍니다.

using System;
using System.Globalization;

public class Example2
{
    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

일반적으로 속성 변경 LongDatePattern 은 속성에도 영향을 FullDateTimePattern 줍니다. 이 속성은 "F" 표준 형식 문자열에서 반환된 결과 문자열을 정의합니다. 원래 전체 날짜 및 시간 패턴을 유지하기 위해 예제에서는 속성이 수정된 후 속성에 FullDateTimePattern 할당된 원래 사용자 지정 형식 문자열을 LongDatePattern 다시 할당합니다.

12시간 시계에서 24시간 시계로 변경

.NET의 많은 문화권에서 시간은 12시간 시계와 AM/PM 지정자를 사용하여 표현됩니다. 다음 예제에서는 12시간 시계를 사용하는 모든 시간 형식을 24시간 클록을 사용하는 형식으로 바꾸는 메서드를 정의 ReplaceWith24HourClock 합니다.

using System;
using System.Globalization;
using System.Text.RegularExpressions;

public class Example5
{
    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

이 예제에서는 정규식을 사용하여 형식 문자열을 수정합니다. 정규식 패턴 @"^(?<openAMPM>\s*t+\s*)? (?(openAMPM) h+(?<nonHours>[^ht]+)$ | \s*h+(?<nonHours>[^ht]+)\s*t+) 은 다음과 같이 정의됩니다.

패턴 설명
^ 문자열의 시작 부분에서 검색을 시작합니다.
(?<openAMPM>\s*t+\s*)? 공백 문자가 0개 또는 1개 이상인 다음 문자 "t"를 한 번 이상 찾은 다음 0개 이상의 공백 문자를 찾습니다. 이 캡처링 그룹의 이름은 openAMPM다음과 같습니다.
(?(openAMPM) h+(?<nonHours>[^ht]+)$ openAMPM 그룹에 일치하는 문자가 있는 경우 문자 "h"를 한 번 이상 일치시킨 다음 " h" 또는 "t"가 없는 하나 이상의 문자를 잇습니다. 일치 항목은 문자열의 끝에 끝납니다. "h" 후에 캡처된 모든 문자는 캡처 nonHours링 그룹에 포함됩니다.
&#124; \s*h+(?<nonHours>[^ht]+)\s*t+) openAMPM 그룹에 일치하는 문자가 없으면 문자 "h"를 한 번 이상 일치시킨 다음 " h" 또는 "t"가 아닌 하나 이상의 문자와 0개 이상의 공백 문자를 찾습니다. 마지막으로 하나 이상의 문자 "t"를 일치시킬 수 있습니다. "h" 뒤와 공백 앞에 캡처된 모든 문자와 "t"는 명명 nonHours된 캡처링 그룹에 포함됩니다.

캡처링 그룹에는 nonHours 사용자 지정 날짜 및 시간 형식 문자열의 분 및 두 번째 구성 요소와 시간 구분 기호가 포함됩니다. 대체 패턴 HH${nonHours} 은 이러한 요소에 부분 문자열 "HH"를 추가합니다.

날짜에 연대 표시 및 변경

다음 예제에서는 en-US 문화권의 서식 규칙을 나타내는 개체의 속성에 "g" 사용자 지정 서식 지정자를 LongDatePattern 추가합니다. 이 추가는 다음 세 가지 표준 형식 문자열에 영향을 줍니다.

  • 속성에 직접 LongDatePattern 매핑되는 "D"(긴 날짜) 표준 형식 문자열입니다.

  • "f"(전체 날짜/짧은 시간) 표준 형식 문자열로, 및 속성에 의해 생성된 부분 문자열을 연결하는 결과 문자열을 LongDatePatternShortTimePattern 생성합니다.

  • 속성에 직접 FullDateTimePattern 매핑되는 "F"(전체 날짜/긴 시간) 표준 서식 문자열입니다. 이 속성 값을 명시적으로 설정하지 않았기 때문에 속성과 LongTimePattern 속성을 연결 LongDatePattern 하여 동적으로 생성됩니다.

이 예제에서는 달력에 단일 연대가 있는 문화권의 연대 이름을 변경하는 방법도 보여 줍니다. 이 경우 en-US 문화권은 개체로 표현되는 그레고리오력(Gregorian Calendar)을 GregorianCalendar 사용합니다. 이 클래스는 GregorianCalendar A.D.(안노 도미니)라는 이름의 단일 시대를 지원합니다. 이 예제에서는 속성에 할당된 FullDateTimePattern 형식 문자열의 "g" 사용자 지정 형식 지정자를 리터럴 문자열로 바꿔 연대 이름을 C.E.(Common Era)로 변경합니다. 연대 이름은 일반적으로 .NET 또는 운영 체제에서 제공하는 문화권 테이블의 프라이빗 데이터에서 메서드에 의해 GetEraName 반환되므로 리터럴 문자열을 사용해야 합니다.

using System;
using System.Globalization;

public class Example4
{
    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

날짜 및 시간 문자열 구문 분석

구문 분석에서는 날짜 및 시간의 문자열 표현을 값으로 DateTimeDateTimeOffset 변환합니다. 이러한 형식에는 구문 분석 작업을 지원하는 메서드, 및 TryParseExact 메서드가 모두 포함ParseExactParseTryParse됩니다. 및 메서드는 Parse 다양한 형식을 가질 수 있는 문자열을 변환하는 TryParseExact 반면 ParseExact 문자열에는 정의된 형식 또는 형식이 있어야 TryParse 합니다. 구문 분석 작업이 실패 Parse 하고 ParseExact 예외를 throw하는 반면 TryParseTryParseExact 에 .false

구문 분석 메서드는 암시적 또는 명시적으로 열거형 값을 사용하여 DateTimeStyles 구문 분석할 문자열에 있을 수 있는 스타일 요소(예: 선행, 후행 또는 내부 공백)와 구문 분석된 문자열 또는 누락된 요소를 해석하는 방법을 결정합니다. 또는 TryParse 메서드를 DateTimeStyles 호출 Parse 할 때 값을 제공하지 않으면 기본값은 DateTimeStyles.AllowWhiteSpaces, 플래그 및 DateTimeStyles.AllowInnerWhite 플래그를 포함하는 DateTimeStyles.AllowLeadingWhiteDateTimeStyles.AllowTrailingWhite복합 스타일입니다. 및 TryParseExact 메서드의 ParseExact 경우 기본값은 입력 문자열이 DateTimeStyles.None특정 사용자 지정 날짜 및 시간 형식 문자열에 정확하게 해당해야 합니다.

구문 분석 메서드는 구문 분석할 문자열에서 발생할 수 있는 특정 기호 및 패턴을 정의하는 개체를 암시적으로 또는 명시적으로 사용합니다 DateTimeFormatInfo . 개체 DateTimeFormatInfoDateTimeFormatInfo 제공하지 않으면 현재 문화권의 개체가 기본적으로 사용됩니다. 날짜 및 시간 문자열 구문 분석에 대한 자세한 내용은 개별 구문 분석 메서드(예: DateTime.Parse, DateTime.TryParseDateTimeOffset.ParseExactDateTimeOffset.TryParseExact)를 참조하세요.

다음 예제에서는 구문 분석 날짜 및 시간 문자열의 문화권 구분 특성을 보여 줍니다. en-US, en-GB, fr-FR 및 fi-FI 문화권의 규칙을 사용하여 두 날짜 문자열을 구문 분석하려고 합니다. en-US 문화권에서 2014년 8월 18일로 해석되는 날짜는 18이 월 번호로 해석되기 때문에 다른 세 문화권에서 예외를 throw FormatException 합니다. 2015년 1월 2일은 en-US 문화에서 첫 번째 달의 둘째 날로 구문 분석되지만 다시 기본 문화권에서 두 번째 달의 첫째 날로 구문 분석됩니다.

using System;
using System.Globalization;

public class ParseEx1
{
    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

날짜 및 시간 문자열은 일반적으로 두 가지 이유로 구문 분석됩니다.

  • 사용자 입력을 날짜 및 시간 값으로 변환합니다.
  • 날짜 및 시간 값을 왕복하려면 즉, 이전에 문자열로 serialize된 날짜 및 시간 값을 역직렬화합니다.

다음 섹션에서는 이러한 두 작업에 대해 자세히 설명합니다.

사용자 문자열 구문 분석

사용자가 입력한 날짜 및 시간 문자열을 구문 분석할 때는 사용자가 만들었을 수 있는 사용자 지정을 포함하여 사용자의 문화권 설정을 반영하는 개체를 항상 인스턴스화 DateTimeFormatInfo 해야 합니다. 그렇지 않으면 날짜 및 시간 개체에 잘못된 값이 있을 수 있습니다. 사용자 문화권 사용자 지정을 반영하는 개체를 DateTimeFormatInfo 인스턴스화하는 방법에 대한 자세한 내용은 DateTimeFormatInfo 및 동적 데이터 섹션을 참조하세요.

다음 예제에서는 사용자 문화권 설정을 반영하는 구문 분석 작업과 그렇지 않은 구문 분석 작업의 차이점을 보여 줍니다. 이 경우 기본 시스템 문화권은 en-US이지만 사용자는 제어판, 지역 및 언어를 사용하여 짧은 날짜 패턴을 기본값인 "M/d/yyyy"에서 "yy/MM/dd"로 변경했습니다. 사용자가 사용자 설정을 반영하는 문자열을 입력하고 사용자 설정(재정의)도 반영하는 개체에 의해 DateTimeFormatInfo 문자열을 구문 분석하면 구문 분석 작업이 올바른 결과를 반환합니다. 그러나 문자열이 표준 en-US culture 설정을 반영하는 개체에 의해 DateTimeFormatInfo 구문 분석되는 경우 구문 분석 메서드는 14를 연도의 마지막 두 자리가 아닌 월 수로 해석하기 때문에 예외를 throw FormatException 합니다.

using System;
using System.Globalization;

public class ParseEx2
{
    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

날짜 및 시간 데이터 직렬화 및 역직렬화

직렬화된 날짜 및 시간 데이터는 왕복할 것으로 예상됩니다. 즉, 직렬화되고 역직렬화된 모든 값은 동일해야 합니다. 날짜 및 시간 값이 시간에서 한 순간을 나타내는 경우 역직렬화된 값은 복원된 시스템의 문화권 또는 표준 시간대에 관계없이 동일한 시간을 나타내야 합니다. 왕복 날짜 및 시간 데이터를 성공적으로 사용하려면 속성에서 반환 InvariantInfo 하는 고정 문화권의 규칙을 사용하여 데이터를 생성하고 구문 분석해야 합니다. 서식 지정 및 구문 분석 작업은 기본 문화권의 규칙을 반영해서는 안 됩니다. 기본 문화권 설정을 사용하는 경우 데이터의 이식성이 엄격하게 제한됩니다. 문화권별 설정이 serialize된 스레드의 설정과 동일한 스레드에서만 역직렬화할 수 있습니다. 경우에 따라 동일한 시스템에서 데이터를 성공적으로 직렬화하고 역직렬화할 수 없다는 의미입니다.

날짜 및 시간 값의 시간 구성 요소가 중요한 경우 UTC로 변환하고 "o" 또는 "r" 표준 형식 문자열을 사용하여 serialize해야 합니다. 그런 다음 구문 분석 메서드를 호출하고 고정 문화권과 함께 적절한 형식 문자열을 인수로 provider 전달하여 시간 데이터를 복원할 수 있습니다.

다음 예제에서는 날짜 및 시간 값을 라운드트립하는 프로세스를 보여 줍니다. 미국 태평양 시간을 관찰하고 현재 문화권이 en-US인 시스템에서 날짜와 시간을 직렬화합니다.

using System;
using System.Globalization;
using System.IO;

public class SerializeEx1
{
    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)

브뤼셀, 코펜하겐, 마드리드 및 파리 표준 시간대의 시스템에 대한 데이터를 역직렬화하며 현재 문화는 fr-FR입니다. 복원된 날짜는 원래 날짜보다 9시간 늦습니다. 이는 UTC보다 8시간 뒤에서 UTC보다 1시간 앞당기는 표준 시간대 조정을 반영합니다. 원래 날짜와 복원된 날짜는 모두 동일한 시간을 나타냅니다.

using System;
using System.Globalization;
using System.IO;

public class SerializeEx2
{
    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