C# 날짜 문자열을 DateTime으로 변환 방법

문자열이지만 값 형태가 날짜인 경우가 있습니다.

여러 처리를 위해 날짜형태인 문자열 값을 DateTime으로 변경해야 하는 경우가 있습니다.

DateTime의 파싱을 사용해 문자열을 DateTime으로 변환하는 방법을 알아보겠습니다.

 

Parse

문자열을 Parse를 사용해 DateTime으로 변환하는 방법을 보겠습니다.

샘플을 보면서 결과값을 확인해보겠습니다.

using System;

namespace Sample
{
	class Sample
	{
		static void Main(string[] args)
		{
            string dateStr = "2024-11-25 19:29:12.312562";

            DateTime dateTime = DateTime.Parse(dateStr);
            Console.WriteLine(dateTime);
		}
	}
}

 

결과

11/25/2024 19:29:12

 

문자열에 대입되어 있는 날짜값이 DateTime 형태로 출력되었습니다.

샘플 데이터에서는 시간도 같이 값이 설정되어 있지만 날짜만 있어도 DateTime 변환이 가능합니다.

샘플을 보면서 확인해보겠습니다.

using System;

namespace Sample
{
	class Sample
	{
		static void Main(string[] args)
		{
            string str = "2024-11-25 19:29:12.312562";
            Console.WriteLine(DateTime.Parse(str));

            str = "2024-11-25 19:29:12";
            Console.WriteLine(DateTime.Parse(str));

            str = "2024-11-25 19:29";
            Console.WriteLine(DateTime.Parse(str));

            str = "2024-11-25";
            Console.WriteLine(DateTime.Parse(str));

            str = "25 Nov 2024";
            Console.WriteLine(DateTime.Parse(str));
		}
	}
}

 

결과

11/25/2024 19:29:12
11/25/2024 19:29:12
11/25/2024 19:29:00
11/25/2024 00:00:00
11/25/2024 00:00:00

 

시간 지정없이 날짜만 지정해도 DateTime 형태로 변환되었습니다.

하지만 시간은 기본값인 00:00:00으로 자동으로 설정이 됩니다.

 

 

ParseExact

문자열을 DateTime 변환할때 지정된 형식만 변환 할 수 있습니다.

지정된 형식의 문자열 날짜값만 변환하게 하려면 ParseExact를 사용합니다.

ParseExact 작성 방법을 먼저 보겠습니다.

ParseExact(문자열, 날짜 포맷, 지역 정보)

 

샘플을 보면서 사용 방법을 알아보겠습니다.

using System;
using System.Globalization;

namespace Sample
{
	class Sample
	{
		static void Main(string[] args)
		{
            string[] formats = new[] {
                    "yyyyMMdd",
                    "yyyy/MM/dd HH:mm:ss"
                };
            CultureInfo provider = new CultureInfo("ko-KR");

            // yyyyMMdd 포맷
            string str = "20241125";
            Console.WriteLine(DateTime.ParseExact(str, formats, provider));

            // yyyy/MM/dd HH:mm:ss 포맷
            str = "2024/11/25 14:30:40";
            Console.WriteLine(DateTime.ParseExact(str, formats, provider));

            // 지정된 포맷이 없어 에러 발생
			str = "2024/11/25 14:30";
            Console.WriteLine(DateTime.ParseExact(str, formats, provider));
		}
	}
}

 

결과

11/25/2024 00:00:00
11/25/2024 14:30:40



Unhandled Exception:
System.FormatException: String was not recognized as a valid DateTime.
  at System.DateTimeParse.ParseExactMultiple (System.ReadOnlySpan`1[T] s, System.String[] formats, System.Globalization.DateTimeFormatInfo dtfi, System.Globalization.DateTimeStyles style) [0x0002b] in <de882a77e7c14f8ba5d298093dde82b2>:0 
  at System.DateTime.ParseExact (System.ReadOnlySpan`1[T] s, System.String[] formats, System.IFormatProvider provider, System.Globalization.DateTimeStyles style) [0x00013] in <de882a77e7c14f8ba5d298093dde82b2>:0 
  at Sample.Sample.Main (System.String[] args) [0x0006d] in <683997e9106e4bf19fa8a1f760c96b3c>:0 
[ERROR] FATAL UNHANDLED EXCEPTION: System.FormatException: String was not recognized as a valid DateTime.
  at System.DateTimeParse.ParseExactMultiple (System.ReadOnlySpan`1[T] s, System.String[] formats, System.Globalization.DateTimeFormatInfo dtfi, System.Globalization.DateTimeStyles style) [0x0002b] in <de882a77e7c14f8ba5d298093dde82b2>:0 
  at System.DateTime.ParseExact (System.ReadOnlySpan`1[T] s, System.String[] formats, System.IFormatProvider provider, System.Globalization.DateTimeStyles style) [0x00013] in <de882a77e7c14f8ba5d298093dde82b2>:0 
  at Sample.Sample.Main (System.String[] args) [0x0006d] in <683997e9106e4bf19fa8a1f760c96b3c>:0 

 

formats 변수에 지정한 형태의 포맷의 문자열만 DateTime로 변환을 합니다.

지정한 형태의 포맷이 아닌 경우에는 에러가 발생합니다.

지역 정보에는 CultureInfo를 사용해 지정 할 수 있습니다.

많이 사용되는 지역 정보는 다음과 같습니다.

설정 값내용
ko-KR한국어(한국)
en-US영어(미국)
ja-JP일본어(일본)
zh-CN중국어(중국)

 

 

TryParse, TryParseExact

문자열을 DateTime으로 변환할때 문자열 값이 날짜 범위의 값이 아니거나 ParseExact에 지정한 포맷이 아닌 경우에는 에러가 발생합니다.

이러한 에러를 미리 체크 하는 방법으로 TryParse 또는 TryParseExact를 사용할 수 있습니다.

사용 방법을 샘플을 보면서 확인해보겠습니다.

using System;
using System.Globalization;

namespace Sample
{
	class Sample
	{
		static void Main(string[] args)
		{
            
            // TryParse 사용 방법 예제
            string str = "20244105";
            DateTime datetime;

            if (DateTime.TryParse(str, out datetime)) {
                Console.WriteLine(datetime);
            } else {
                Console.WriteLine(str + "값은 날짜 범위가 아닙니다. ");
            }
            
            
            
            // TryParseExact 사용 방법 예제
             string[] formats = new[] {
                    "yyyyMMdd",
                    "MM/dd/yyyy HH:mm:ss"
                };
            CultureInfo provider = new CultureInfo("ko-KR");

            str = "2024/11/25 14:30";
 

            if (DateTime.TryParseExact(str, formats, provider,
                    DateTimeStyles.None, out datetime)) {
                Console.WriteLine(datetime);
            } else {
                Console.WriteLine(str + "값은 지정된 포맷이 아닙니다. ");
            }
		}
	}
}

 

결과

20244105값은 날짜 범위가 아닙니다.
2024/11/25 14:30값은 지정된 포맷이 아닙니다. 

 

TryParse TryParseExact는 단순히 체크를 하는 것이 아니라 문제가 없으면 DateTime으로 형변환을 합니다.

하지만 형변환중에 에러가 발생하면 내부에서 FormatException 예외처리를 하고 false 값을 반환합니다.

 

댓글