DateTime.ToUniversalTime DateTime.ToUniversalTime DateTime.ToUniversalTime DateTime.ToUniversalTime Method

정의

현재 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

반환

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 속성이 영향을 줍니다 합니다 ToLocalTimeToUniversalTime 변환 메서드.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 'Sample

'
'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 오프셋에 대 한 자세한 내용은 참조 하세요. TimeZone.GetUtcOffset합니다.For more information about the UTC offset, see TimeZone.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 XPWindows XP 체제는 ToUniversalTime 메서드 현지 시간에서 UTC로 변환 하는 경우에 현재 조정 규칙을 인식 합니다.On Windows XPWindows 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 개체를 현지 시간으로 간주 됩니다 및 변환이 수행 되며 처럼 KindLocal합니다.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 XPWindows XP 체제는 ToUniversalTime() 하위 수준 (즉, 날짜를 현재 조정의 시작 날짜 보다 이전 날짜를 포함 하는 모든 날짜에 적용 하는 현지 표준 시간대에 대 한 현재 조정 규칙을 인식 하는 메서드 규칙)입니다.On Windows XPWindows 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 XPWindows XP 필요한 정확한 로컬 날짜 및 시간을 계산 해야 사용 하 여이 문제 해결 합니다 FindSystemTimeZoneById(String) 검색 하는 메서드를 TimeZoneInfo 현지 표준 시간대에 해당 하는 개체를 호출 해당 ConvertTimeToUtc(DateTime, TimeZoneInfo) 메서드.Applications running on Windows XPWindows 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 XPWindows XP 미국의 시스템 표시합니다.The following example illustrates the difference between the ToUniversalTime() and ConvertTimeToUtc(DateTime, TimeZoneInfo) methods on a Windows XPWindows XP system in the U.S. Pacific Time zone. 2006 날짜에는 현재 표준 시간대 조정 규칙 (2007 적용 됨)를 적용 하는 첫 번째 두 메서드 호출 됩니다.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.

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

적용 대상

추가 정보