DateTime.ToUniversalTime 메서드

정의

현재 DateTime 개체의 값을 UTC(협정 세계시)로 변환합니다.Converts the value of the current DateTime object to Coordinated Universal Time (UTC).

public:
 DateTime ToUniversalTime();
public DateTime ToUniversalTime ();
member this.ToUniversalTime : unit -> DateTime
Public Function ToUniversalTime () As DateTime

반환

DateTime

Kind 속성이 Utc이고, 현재 DateTime 개체의 값에 해당하는 UTC가 값인 개체입니다. 변환된 값이 너무 커서 MaxValue 개체로 표현할 수 없는 경우 DateTime이고, 변환된 값이 너무 작아서 MinValue 개체로 표현할 수 없는 경우 DateTime입니다.An object whose Kind property is Utc, and whose value is the UTC equivalent to the value of the current DateTime object, or MaxValue if the converted value is too large to be represented by a DateTime object, or MinValue if the converted value is too small to be represented by a DateTime object.

예제

다음 예제는 ToUniversalTime 메서드.The following example demonstrates the ToUniversalTime method.

using namespace System;

void main()
{
   Console::WriteLine("Enter a date and time.");
   String^ strDateTime = Console::ReadLine();

   DateTime localDateTime, univDateTime;
   try
   {
      localDateTime = DateTime::Parse(strDateTime);
      univDateTime = localDateTime.ToUniversalTime();
    
      Console::WriteLine("{0} local time is {1} universal time.",
                         localDateTime, univDateTime );
   }
   catch (FormatException^) 
   {
      Console::WriteLine("Invalid format.");
      return;
   }

   Console::WriteLine("Enter a date and time in universal time.");
   strDateTime = Console::ReadLine();

   try
   {
      univDateTime = DateTime::Parse(strDateTime);
      localDateTime = univDateTime.ToLocalTime();
  
      Console::WriteLine("{0} universal time is {1} local time.",
                         univDateTime, localDateTime );
   }
   catch (FormatException^) 
   {
      Console::WriteLine("Invalid format.");
      return;
   }
}
// The example displays output like the following when run on a 
// computer whose culture is en-US in the Pacific Standard Time zone:
//     Enter a date and time.
//     12/10/2015 6:18 AM
//     12/10/2015 6:18:00 AM local time is 12/10/2015 2:18:00 PM universal time.
//     Enter a date and time in universal time.
//     12/20/2015 6:42:00
//     12/20/2015 6:42:00 AM universal time is 12/19/2015 10:42:00 PM local time.
using System;

class Example
{
    static void Main()
    {
        DateTime localDateTime, univDateTime;
        
        Console.WriteLine("Enter a date and time.");
        string strDateTime = Console.ReadLine();

        try {
            localDateTime = DateTime.Parse(strDateTime);
            univDateTime = localDateTime.ToUniversalTime();

            Console.WriteLine("{0} local time is {1} universal time.",
                                localDateTime,
                                    univDateTime);
        }
        catch (FormatException) {
            Console.WriteLine("Invalid format.");
            return;
        }

        Console.WriteLine("Enter a date and time in universal time.");
        strDateTime = Console.ReadLine();

        try {
            univDateTime = DateTime.Parse(strDateTime);
            localDateTime = univDateTime.ToLocalTime();

            Console.WriteLine("{0} universal time is {1} local time.",
                                     univDateTime,
                                     localDateTime);
        }
        catch (FormatException) {
            Console.WriteLine("Invalid format.");
            return;
        }
    }
}
// The example displays output like the following when run on a
// computer whose culture is en-US in the Pacific Standard Time zone:
//     Enter a date and time.
//     12/10/2015 6:18 AM
//     12/10/2015 6:18:00 AM local time is 12/10/2015 2:18:00 PM universal time.
//     Enter a date and time in universal time.
//     12/20/2015 6:42:00
//     12/20/2015 6:42:00 AM universal time is 12/19/2015 10:42:00 PM local time.
Module Example
    Sub Main()
      Dim localDateTime, univDateTime As DateTime
      
      Console.WriteLine("Enter a date and time.")
      Dim strDateTime As String = Console.ReadLine()
      Try
         localDateTime = DateTime.Parse(strDateTime)
         univDateTime = localDateTime.ToUniversalTime()
         Console.WriteLine("{0} local time is {1} universal time.", 
                           localDateTime, univDateTime)
      Catch exp As FormatException
         Console.WriteLine("Invalid format.")
      End Try

      Console.WriteLine("Enter a date and time in universal time.")
      strDateTime = Console.ReadLine()
      Try
         univDateTime = DateTime.Parse(strDateTime)
         localDateTime = univDateTime.ToLocalTime()
  
         Console.WriteLine("{0} universal time is {1} local time.", _
                           univDateTime, localDateTime)
      Catch exp As FormatException
         Console.WriteLine("Invalid format.")
      End Try
    End Sub
End Module
' The example displays output like the following when run on a 
' computer whose culture is en-US in the Pacific Standard Time zone:
'     Enter a date and time.
'     12/10/2015 6:18 AM
'     12/10/2015 6:18:00 AM local time is 12/10/2015 2:18:00 PM universal time.
'     Enter a date and time in universal time.
'     12/20/2015 6:42:00
'     12/20/2015 6:42:00 AM universal time is 12/19/2015 10:42:00 PM local time.

다음 예제에서는 메서드를 사용 하 여 SpecifyKind Kind 속성이 ToLocalTime 및 변환 메서드에 영향을 주는 방법을 보여 줍니다 ToUniversalTime .The following example uses the SpecifyKind method to demonstrate how the Kind property influences the ToLocalTime and ToUniversalTime conversion methods.

// This code example demonstrates the DateTime Kind, Now, and
// UtcNow properties, and the SpecifyKind(), ToLocalTime(),
// and ToUniversalTime() methods.

using System;

class Sample
{
    public static void Main()
    {
// Get the date and time for the current moment, adjusted
// to the local time zone.

    DateTime saveNow = DateTime.Now;

// Get the date and time for the current moment expressed
// as coordinated universal time (UTC).

    DateTime saveUtcNow = DateTime.UtcNow;
    DateTime myDt;

// Display the value and Kind property of the current moment
// expressed as UTC and local time.

    DisplayNow("UtcNow: ..........", saveUtcNow);
    DisplayNow("Now: .............", saveNow);
    Console.WriteLine();

// Change the Kind property of the current moment to
// DateTimeKind.Utc and display the result.

    myDt = DateTime.SpecifyKind(saveNow, DateTimeKind.Utc);
    Display("Utc: .............", myDt);

// Change the Kind property of the current moment to
// DateTimeKind.Local and display the result.

    myDt = DateTime.SpecifyKind(saveNow, DateTimeKind.Local);
    Display("Local: ...........", myDt);

// Change the Kind property of the current moment to
// DateTimeKind.Unspecified and display the result.

    myDt = DateTime.SpecifyKind(saveNow, DateTimeKind.Unspecified);
    Display("Unspecified: .....", myDt);
    }

// Display the value and Kind property of a DateTime structure, the
// DateTime structure converted to local time, and the DateTime
// structure converted to universal time.

    public static string datePatt = @"M/d/yyyy hh:mm:ss tt";
    public static void Display(string title, DateTime inputDt)
    {
    DateTime dispDt = inputDt;
    string dtString;

// Display the original DateTime.

    dtString = dispDt.ToString(datePatt);
    Console.WriteLine("{0} {1}, Kind = {2}",
                      title, dtString, dispDt.Kind);

// Convert inputDt to local time and display the result.
// If inputDt.Kind is DateTimeKind.Utc, the conversion is performed.
// If inputDt.Kind is DateTimeKind.Local, the conversion is not performed.
// If inputDt.Kind is DateTimeKind.Unspecified, the conversion is
// performed as if inputDt was universal time.

    dispDt = inputDt.ToLocalTime();
    dtString = dispDt.ToString(datePatt);
    Console.WriteLine("  ToLocalTime:     {0}, Kind = {1}",
                      dtString, dispDt.Kind);

// Convert inputDt to universal time and display the result.
// If inputDt.Kind is DateTimeKind.Utc, the conversion is not performed.
// If inputDt.Kind is DateTimeKind.Local, the conversion is performed.
// If inputDt.Kind is DateTimeKind.Unspecified, the conversion is
// performed as if inputDt was local time.

    dispDt = inputDt.ToUniversalTime();
    dtString = dispDt.ToString(datePatt);
    Console.WriteLine("  ToUniversalTime: {0}, Kind = {1}",
                      dtString, dispDt.Kind);
    Console.WriteLine();
    }

// Display the value and Kind property for DateTime.Now and DateTime.UtcNow.

    public static void DisplayNow(string title, DateTime inputDt)
    {
    string dtString = inputDt.ToString(datePatt);
    Console.WriteLine("{0} {1}, Kind = {2}",
                      title, dtString, inputDt.Kind);
    }
}

/*
This code example produces the following results:

UtcNow: .......... 5/6/2005 09:34:42 PM, Kind = Utc
Now: ............. 5/6/2005 02:34:42 PM, Kind = Local

Utc: ............. 5/6/2005 02:34:42 PM, Kind = Utc
  ToLocalTime:     5/6/2005 07:34:42 AM, Kind = Local
  ToUniversalTime: 5/6/2005 02:34:42 PM, Kind = Utc

Local: ........... 5/6/2005 02:34:42 PM, Kind = Local
  ToLocalTime:     5/6/2005 02:34:42 PM, Kind = Local
  ToUniversalTime: 5/6/2005 09:34:42 PM, Kind = Utc

Unspecified: ..... 5/6/2005 02:34:42 PM, Kind = Unspecified
  ToLocalTime:     5/6/2005 07:34:42 AM, Kind = Local
  ToUniversalTime: 5/6/2005 09:34:42 PM, Kind = Utc

*/

' This code example demonstrates the DateTime Kind, Now, and
' UtcNow properties, and the SpecifyKind(), ToLocalTime(), 
' and ToUniversalTime() methods.
Class Sample
    Public Shared Sub Main() 
        ' Get the date and time for the current moment, adjusted 
        ' to the local time zone.
        Dim saveNow As DateTime = DateTime.Now
        
        ' Get the date and time for the current moment expressed 
        ' as coordinated universal time (UTC).
        Dim saveUtcNow As DateTime = DateTime.UtcNow
        Dim myDt As DateTime
        
        ' Display the value and Kind property of the current moment 
        ' expressed as UTC and local time.
        DisplayNow("UtcNow: ..........", saveUtcNow)
        DisplayNow("Now: .............", saveNow)
        Console.WriteLine()
        
        ' Change the Kind property of the current moment to 
        ' DateTimeKind.Utc and display the result.
        myDt = DateTime.SpecifyKind(saveNow, DateTimeKind.Utc)
        Display("Utc: .............", myDt)
        
        ' Change the Kind property of the current moment to 
        ' DateTimeKind.Local and display the result.
        myDt = DateTime.SpecifyKind(saveNow, DateTimeKind.Local)
        Display("Local: ...........", myDt)
        
        ' Change the Kind property of the current moment to 
        ' DateTimeKind.Unspecified and display the result.
        myDt = DateTime.SpecifyKind(saveNow, DateTimeKind.Unspecified)
        Display("Unspecified: .....", myDt)
    End Sub
    
    ' Display the value and Kind property of a DateTime structure, the 
    ' DateTime structure converted to local time, and the DateTime 
    ' structure converted to universal time. 

    Public Shared datePatt As String = "M/d/yyyy hh:mm:ss tt"
    
    Public Shared Sub Display(ByVal title As String, ByVal inputDt As DateTime) 
        Dim dispDt As DateTime = inputDt
        Dim dtString As String
        
        ' Display the original DateTime.
        dtString = dispDt.ToString(datePatt)
        Console.WriteLine("{0} {1}, Kind = {2}", title, dtString, dispDt.Kind)
        
        ' Convert inputDt to local time and display the result. 
        ' If inputDt.Kind is DateTimeKind.Utc, the conversion is performed.
        ' If inputDt.Kind is DateTimeKind.Local, the conversion is not performed.
        ' If inputDt.Kind is DateTimeKind.Unspecified, the conversion is 
        ' performed as if inputDt was universal time.
        dispDt = inputDt.ToLocalTime()
        dtString = dispDt.ToString(datePatt)
        Console.WriteLine("  ToLocalTime:     {0}, Kind = {1}", dtString, dispDt.Kind)
        
        ' Convert inputDt to universal time and display the result. 
        ' If inputDt.Kind is DateTimeKind.Utc, the conversion is not performed.
        ' If inputDt.Kind is DateTimeKind.Local, the conversion is performed.
        ' If inputDt.Kind is DateTimeKind.Unspecified, the conversion is 
        ' performed as if inputDt was local time.
        dispDt = inputDt.ToUniversalTime()
        dtString = dispDt.ToString(datePatt)
        Console.WriteLine("  ToUniversalTime: {0}, Kind = {1}", dtString, dispDt.Kind)
        Console.WriteLine()
    End Sub
    
    
    ' Display the value and Kind property for DateTime.Now and DateTime.UtcNow.

    Public Shared Sub DisplayNow(ByVal title As String, ByVal inputDt As DateTime) 
        Dim dtString As String = inputDt.ToString(datePatt)
        Console.WriteLine("{0} {1}, Kind = {2}", title, dtString, inputDt.Kind)
    End Sub
End Class

'
'This code example produces the following results:
'
'UtcNow: .......... 5/6/2005 09:34:42 PM, Kind = Utc
'Now: ............. 5/6/2005 02:34:42 PM, Kind = Local
'
'Utc: ............. 5/6/2005 02:34:42 PM, Kind = Utc
'  ToLocalTime:     5/6/2005 07:34:42 AM, Kind = Local
'  ToUniversalTime: 5/6/2005 02:34:42 PM, Kind = Utc
'
'Local: ........... 5/6/2005 02:34:42 PM, Kind = Local
'  ToLocalTime:     5/6/2005 02:34:42 PM, Kind = Local
'  ToUniversalTime: 5/6/2005 09:34:42 PM, Kind = Utc
'
'Unspecified: ..... 5/6/2005 02:34:42 PM, Kind = Unspecified
'  ToLocalTime:     5/6/2005 07:34:42 AM, Kind = Local
'  ToUniversalTime: 5/6/2005 09:34:42 PM, Kind = Utc
'

설명

Utc (협정 세계시)는 현지 시간에서 UTC 오프셋을 뺀 값과 같습니다.The Coordinated Universal Time (UTC) is equal to the local time minus the UTC offset. UTC 오프셋에 대 한 자세한 내용은을 참조 하십시오 TimeZoneInfo.GetUtcOffset .For more information about the UTC offset, see TimeZoneInfo.GetUtcOffset. 변환은 현재 개체가 나타내는 시간에 적용 되는 일광 절약 시간 규칙도 고려 합니다 DateTime .The conversion also takes into account the daylight saving time rule that applies to the time represented by the current DateTime object.

중요

Windows XP 시스템에서 메서드는 ToUniversalTime 현지 시간을 UTC로 변환할 때 현재 조정 규칙만 인식 합니다.On Windows XP systems, the ToUniversalTime method recognizes only the current adjustment rule when converting from local time to UTC. 따라서 현재 조정 규칙이 적용 되기 전의 기간의 변환은 현지 시간과 UTC의 차이를 정확 하 게 반영 하지 않을 수 있습니다.As a result, conversions for periods before the current adjustment rule came into effect may not accurately reflect the difference between local time and UTC.

.NET Framework 버전 2.0부터 메서드에서 반환 되는 값은 ToUniversalTime Kind 현재 개체의 속성에 의해 결정 됩니다 DateTime .Starting with the .NET Framework version 2.0, the value returned by the ToUniversalTime method is determined by the Kind property of the current DateTime object. 다음 표에서는 가능한 결과에 대해 설명 합니다.The following table describes the possible results.

종류Kind 결과Results
Utc 변환이 수행 되지 않습니다.No conversion is performed.
Local 현재 DateTime 개체가 UTC로 변환 됩니다.The current DateTime object is converted to UTC.
Unspecified 현재 DateTime 개체는 현지 시간으로 간주 되 고가 인 것 처럼 변환이 수행 됩니다 Kind Local .The current DateTime object is assumed to be a local time, and the conversion is performed as if Kind were Local.

참고

ToUniversalTime메서드는 값을 DateTime 현지 시간에서 UTC로 변환 합니다.The ToUniversalTime method converts a DateTime value from local time to UTC. 현지이 아닌 표준 시간대의 시간을 UTC로 변환 하려면 메서드를 사용 TimeZoneInfo.ConvertTimeToUtc(DateTime, TimeZoneInfo) 합니다.To convert the time in a non-local time zone to UTC, use the TimeZoneInfo.ConvertTimeToUtc(DateTime, TimeZoneInfo) method. UTC에서의 오프셋이 알려져 있는 시간을 변환 하려면 메서드를 사용 ToUniversalTime 합니다.To convert a time whose offset from UTC is known, use the ToUniversalTime method.

날짜 및 시간 인스턴스 값이 모호한 시간인 경우이 메서드는 표준 시간인 것으로 가정 합니다.If the date and time instance value is an ambiguous time, this method assumes that it is a standard time. 모호한 시간은 표준 시간 또는 현지 표준 시간대의 일광 절약 시간으로 매핑될 수 있는 것입니다. 날짜 및 시간 인스턴스 값이 잘못 된 시간인 경우이 메서드는 UTC를 반환 하기 위해 현지 표준 시간대의 UTC 오프셋에서 현지 시간을 뺍니다.(An ambiguous time is one that can map either to a standard time or to a daylight saving time in the local time zone) If the date and time instance value is an invalid time, this method simply subtracts the local time from the local time zone's UTC offset to return UTC. (잘못 된 시간은 일광 절약 시간 조정 규칙 애플리케이션 때문에 존재 하지 않는 것입니다.)(An invalid time is one that does not exist because of the application of daylight saving time adjustment rules.)

호출자 참고

ToUniversalTime()메서드는 때때로 현지 시간을 UTC로 변환 하는 데 사용 됩니다.The ToUniversalTime() method is sometimes used to convert a local time to UTC. ToLocalTime()그런 다음 메서드를 호출 하 여 원래 현지 시간을 복원 합니다.The ToLocalTime() method is then called to restore the original local time. 그러나 원래 시간이 현지 표준 시간대에서 잘못 된 시간을 나타내는 경우 두 현지 시간 값은 같지 않습니다.However, if the original time represents an invalid time in the local time zone, the two local time values will not be equal. 추가 정보 및 예제는 메서드를 참조 하세요 ToLocalTime() .For additional information and an example, see the ToLocalTime() method.

Windows XP 시스템에서 메서드는 ToUniversalTime() 현지 표준 시간대에 대 한 현재 조정 규칙만 인식 합니다 .이 규칙은 하위 수준 날짜 (즉, 현재 조정 규칙의 시작 날짜 이전 날짜)를 비롯 한 모든 날짜에 적용 됩니다.On Windows XP systems, the ToUniversalTime() method recognizes only the current adjustment rule for the local time zone, which it applies to all dates, including down-level dates (that is, dates that are earlier than the starting date of the current adjustment rule). 현재 정확한 로컬 날짜 및 시간 계산이 필요한 Windows XP에서 실행 되는 응용 프로그램은 메서드를 사용 하 여 FindSystemTimeZoneById(String) TimeZoneInfo 현지 표준 시간대에 해당 하는 개체를 검색 하 고 해당 메서드를 호출 하 여이 동작을 해결 해야 합니다 ConvertTimeToUtc(DateTime, TimeZoneInfo) .Applications running on Windows XP that require historically accurate local date and time calculations must work around this behavior by using the FindSystemTimeZoneById(String) method to retrieve a TimeZoneInfo object that corresponds to the local time zone and calling its ConvertTimeToUtc(DateTime, TimeZoneInfo) method.

다음 예제에서는 ToUniversalTime() ConvertTimeToUtc(DateTime, TimeZoneInfo) 미국 태평양 표준 시간대에 있는 Windows XP 시스템에서 및 메서드 간의 차이점을 보여 줍니다.The following example illustrates the difference between the ToUniversalTime() and ConvertTimeToUtc(DateTime, TimeZoneInfo) methods on a Windows XP system in the U.S. Pacific Time zone. 처음 두 메서드 호출은 2007에 적용 된 현재 표준 시간대 조정 규칙을 2006의 날짜에 적용 합니다.The first two method calls apply the current time zone adjustment rule (which went into effect in 2007) to a date in 2006. 현재 조정 규칙은 3 월의 두 번째 일요일에 일광 절약 시간으로 전환 하는 데 제공 됩니다. 2006에 적용 된 이전 규칙은 4 월 첫 번째 일요일에 일광 절약 시간으로 전환 하기 위해 제공 됩니다.The current adjustment rule provides for the transition to daylight saving time on the second Sunday of March; the previous rule, which was in effect in 2006, provided for the transition to daylight saving time to occur on the first Sunday of April. 세 번째 메서드 호출만이 기록 날짜 및 시간 변환을 정확 하 게 수행 합니다.Only the third method call accurately performs this historical date and time conversion.

[! ToUniversalTime# 1] [! code-vbToUniversalTime # 1][!code-csharpSystem.DateTime.ToUniversalTime#1] [!code-vbSystem.DateTime.ToUniversalTime#1]

적용 대상

추가 정보