Computer >> 컴퓨터 >  >> 프로그래밍 >> C#

C#에서 현재 DateTime 객체의 값을 UTC(협정 세계시)로 변환하는 방법

C#에서 현재 DateTime 객체의 값을 UTC(Coordinated Universal Time, 협정 세계시)로 변환하려면 ToUniversalTime() 메서드를 사용하면 됩니다. 이 메서드는 현재 객체의 시간 값을 UTC 기준으로 변환한 새로운 DateTime 객체를 반환합니다.

예제 1

다음은 DateTime 객체를 생성한 후 ToUniversalTime() 메서드를 호출하여 UTC로 변환하는 기본적인 예제입니다.

using System;
public class Demo {
   public static void Main() {
      DateTime d = new DateTime(2019, 12, 11, 7, 11, 25);
      Console.WriteLine("Date = {0}", d);
      DateTime res = d.ToUniversalTime();
      Console.WriteLine("String representation = {0}", res);
   }
}

출력 결과

위 코드를 실행하면 다음과 같은 결과가 출력됩니다.

Date = 11/11/2019 7:11:25 AM
String representation = 11/11/2019 7:11:25 AM

예제 2

이번에는 문자열 형태의 날짜와 시간을 DateTime.Parse()로 파싱한 뒤, 이를 UTC로 변환하는 예제를 살펴보겠습니다.

using System;
public class Demo {
   public static void Main() {
      DateTime localDate, universalDate;
      String str = "11/11/2019 4:10:55";
      localDate = DateTime.Parse(str);
      universalDate = localDate.ToUniversalTime();
      Console.WriteLine("Local time = {0} ", localDate);
      Console.WriteLine("Universal time = {0} ", universalDate);
   }
}

출력 결과

위 코드를 실행하면 다음과 같은 결과가 출력됩니다.

Local time = 11/11/2019 4:10:55 AM
Universal time = 11/11/2019 4:10:55 AM

참고 사항

ToUniversalTime() 메서드의 동작은 해당 DateTime 객체의 Kind 속성 값에 따라 달라집니다. Kind가 Local이면 현지 시간을 UTC로 변환하고, Utc이면 변경 없이 그대로 반환합니다. Unspecified인 경우에는 현지 시간으로 간주하여 변환을 수행합니다. 따라서 서버 환경의 시간대 설정에 따라 출력 결과가 달라질 수 있다는 점을 유의해야 합니다.