C#의 DateTime.ToShortTimeString() 메서드는 현재 DateTime 객체의 값을 해당하는 짧은 시간 형식의 문자열로 변환할 때 사용합니다. 이 메서드는 현재 스레드의 문화권(CurrentCulture) 설정에 따라 지정된 짧은 시간 패턴을 기준으로 결과를 반환한다는 점이 특징입니다.
구문
메서드의 기본 구문은 다음과 같습니다.
public string ToShortTimeString ();
예제 1: 현재 날짜와 시간 변환하기
다음 예제는 DateTime.ToShortTimeString() 메서드를 사용하여 현재 시간을 짧은 시간 문자열로 변환하는 방법을 보여줍니다.
using System;
using System.Globalization;
public class Demo {
public static void Main() {
DateTime d = DateTime.Now;
Console.WriteLine("Date = {0}", d);
Console.WriteLine("Current culture = "+CultureInfo.CurrentCulture.Name);
var pattern = CultureInfo.CurrentCulture.DateTimeFormat;
string str = d.ToShortTimeString();
Console.WriteLine("Short time string = {0}", pattern.ShortTimePattern);
Console.WriteLine("Short time string representation = {0}", str);
}
}실행 결과
위 코드를 실행하면 다음과 같은 출력이 생성됩니다.
Date = 10/16/2019 8:59:23 AM Current culture = en-US Short time string = h:mm tt Short time string representation = 8:59 AM
출력 결과를 보면 en-US 문화권에서는 'h:mm tt' 패턴이 적용되어 '오전 8:59' 대신 '8:59 AM' 형태로 표시되는 것을 확인할 수 있습니다.
예제 2: 특정 날짜와 시간 변환하기
이번에는 특정 날짜와 시간을 지정하여 ToShortTimeString() 메서드를 적용해 보겠습니다.
using System;
public class Demo {
public static void Main() {
DateTime d = new DateTime(2019, 11, 11, 7, 11, 25);
Console.WriteLine("Date = {0}", d);
string str = d.ToShortTimeString();
Console.WriteLine("Short time string representation = {0}", str);
}
}실행 결과
위 코드를 실행하면 다음과 같은 출력이 생성됩니다.
Date = 11/11/2019 7:11:25 AM Short time string representation = 7:11 AM
정리
DateTime.ToShortTimeString() 메서드는 별도의 서식 지정 없이 간단하게 시간 부분만 추출하여 표시하고 싶을 때 유용합니다. 다만 반환되는 형식은 실행 환경의 문화권 설정에 따라 달라지므로, 일관된 형식이 필요한 경우에는 ToString() 메서드에 명시적인 형식 문자열을 지정하거나 CultureInfo를 직접 지정하는 것이 좋습니다.