다음을 통해 공유


특정 문화권의 날짜 및 시간 형식 지정

응용 프로그램에서는 DateTime 구조체가 제공하는 메서드를 통해 DateTime 형식에 대해 문화권별 작업을 수행할 수 있습니다. 응용 프로그램에서는 DateTimeFormatInfo 클래스를 사용하여 문화권에 따라 DateTime 형식의 서식을 지정하고 표시할 수 있습니다. 예를 들어 DateTimeFormatInfo.ShortDatePattern을 사용하여 2001년 2월 1일의 형식을 영어(미국) "en-US" 문화권의 경우 2/1/2001로, 영어(영국) "en-GB" 문화권의 경우 01/02/2001로 지정할 수 있습니다.

중립 문화권이 아닌 고정 문화권이나 특정 문화권에 대해서만 DateTimeFormatInfo 개체를 만들 수 있습니다. 중립 문화권에서는 정확한 날짜 형식을 표시할 충분한 정보가 제공되지 않습니다. 응용 프로그램에서 중립 문화권을 사용하여 DateTimeFormatInfo 개체를 만들려고 하면 예외가 throw됩니다. DateTime 형식을 사용하는 방법에 대한 예제 및 자세한 내용은 날짜 및 시간 형식 문자열을 참조하십시오.

다음 코드 예제에서는 DateTimeFormatInfo.ShortDatePattern을 사용하여 Thread.CurrentThread의 현재 문화권이 영어(미국) "en-US"로 설정된 경우와 독일어(독일) "de-DE"로 설정된 경우의 현재 날짜를 표시합니다.

Imports System
Imports System.Globalization
Imports System.Threading

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

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

이 코드를 2001년 7월 9일에 실행하면 다음과 같이 출력됩니다.

7/9/2001
09.07.2001

표준 시간대 작업

DateTime 구조체는 항상 현지 표준 시간대를 사용하여 계산하고 비교합니다. 응용 프로그램에서 DateTime.ParseDateTime.ParseExact 메서드를 사용하는 경우 이 점을 고려해야 합니다. 이러한 메서드는 날짜 및 시간의 문자열 표현을 DateTime 형식으로 변환할 수 있는 오버로드를 제공합니다. 응용 프로그램에서 DateTime 형식의 서식을 특정 문화권에 맞게 지정할 수도 있습니다. 이러한 메서드에 전달하는 문자열에 표준 시간대를 지정하지 않으면 표준 시간대를 조정하지 않고 구문 분석된 날짜와 시간이 검색됩니다. 날짜와 시간은 운영 체제의 표준 시간대 설정을 따릅니다. 응용 프로그램에서 표준 시간대 오프셋을 지정하면 이러한 메서드는 날짜/시간 문자열을 구문 분석하여 이전에는 GMT(그리니치 표준시)라고 불리던 UTC(협정 세계시)로 변환한 다음 로컬 시스템 시간으로 변환합니다.

응용 프로그램에서는 The application should use the DateTime.ToUniversalTime 메서드를 사용하여 로컬 DateTime 형식을 해당 UTC 시간으로 변환해야 합니다. 날짜/시간 문자열을 구문 분석하고 UTC DateTime 형식으로 변환하려면 응용 프로그램에서 DateTime.Parse 메서드 또는 DateTime.ParseExact 메서드에 DateTimeStyles.AdjustToUniversal 열거형 값을 사용해야 합니다.

다음 코드 예제에서는 현지 시간에 대한 DateTime 형식을 만든 다음 해당 UTC 시간으로 변환합니다. 두 형식은 모두 문자열로 변환되며 콘솔에 쓰여집니다. 두 문자열의 차이는 현지 표준 시간대와 UTC 사이의 UTC 오프셋에 해당합니다. 이러한 문자열은 DateTime.ParseExact 메서드를 사용하여 다시 DateTime 형식으로 변환됩니다. utcdt에 저장된 표준 시간대 정보를 캡처하려면 DateTime.ParseExact 메서드의 매개 변수에 DateTimeStyles.AdjustToUniversal 값을 지정해야 합니다. 다양한 표준 시간대의 UTC 오프셋에 대한 자세한 내용은 GetUtcOffset을 참조하십시오.

Imports System
Imports System.Globalization
Imports System.Threading

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

이 코드는 다음과 같이 출력됩니다.

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

DateTime 멤버 작업

DateTime 구조체를 사용할 때는 DateTime.Day 등의 멤버가 그레고리오력을 따른다는 점을 고려해야 합니다. 응용 프로그램에서 현재 달력을 변경하거나 사용자가 제어판의 국가 및 언어 옵션을 통해 날짜 및 시간 설정을 변경해도 DateTime 메서드는 그레고리오력을 사용하여 계산을 수행하므로 이러한 메서드가 수행하는 연산은 사용자 설정의 영향을 받지 않습니다. 응용 프로그램에서 현재 달력에 따라 문화권별 날짜 및 시간 작업을 수행하려면 응용 프로그램에서 DateTimeFormatInfo.Calendar 속성을 사용하여 Calendar 클래스가 제공하는 Calendar.GetDayOfMonth 등의 메서드를 호출해야 합니다. DateTime 멤버와 DateTimeFormatInfo.Calendar 멤버로 검색되는 값의 차이를 보여 주는 예제는 특정 문화권의 달력 사용을 참조하십시오.

DateTime 구조체를 사용할 때는 DateTime 형식이 변경 불가능한 값임에 주의해야 합니다. 따라서 DateTime.AddDays 등의 메서드는 기존 값을 증가시키지 않고 새 DateTime 값을 검색합니다. 다음 예제에서는 dt = dt.AddDays(1) 문을 사용하여 DateTime을 하루씩 증가시키는 방법을 보여 줍니다.

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

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

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

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

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

   }
}

이 코드를 2001년 8월 3일에 실행하면 다음과 같이 출력됩니다.

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

참고 항목

기타 리소스

인코딩 및 지역화

Date and Time Format Strings