날짜 문자열을 DateTime 객체로 변환하는 방법을 소개합니다.
1. DateTime.parse()를 이용한 방법
DateTime.parse(str)는 문자열을 파싱하여 DateTime으로 변환합니다.
namespace Example {
public class Program {
public static void Main(string[] args) {
string dateStr = "2022-12-05 20:09:14.322471";
DateTime dateTime = DateTime.Parse(dateStr);
Console.WriteLine(dateTime);
}
}
}Output:
12/5/2022 8:09:14 PM1.1 다양한 형식의 문자열 파싱
아래와 같이 다양한 형식의 문자열을 파싱할 수 있습니다.
namespace Example {
public class Program {
public static void Main(string[] args) {
string str = "2022-12-05 10:09:14.322471";
Console.WriteLine(DateTime.Parse(str));
str = "2022-12-06 20:09:14";
Console.WriteLine(DateTime.Parse(str));
str = "2022-12-07 22:09";
Console.WriteLine(DateTime.Parse(str));
str = "2022-12-08";
Console.WriteLine(DateTime.Parse(str));
str = "09 Dec 2022";
Console.WriteLine(DateTime.Parse(str));
}
}
}Output:
12/5/2022 10:09:14 AM
12/6/2022 8:09:14 PM
12/7/2022 10:09:00 PM
12/8/2022 12:00:00 AM
12/9/2022 12:00:00 AM1.2 잘못된 날짜 형식, FormatException 에러
기본적으로 지원하지 않는 문자열 형식을 파싱할 때, FormatException 에러가 발생합니다. 예외를 처리하지 않으면 프로그램이 종료됩니다.
string str = "20221205";
Console.WriteLine(DateTime.Parse(str));Output:
Unhandled exception. System.FormatException: String '20221205' was not recognized as a valid DateTime.
at System.DateTime.Parse(String s)2. DateTime.TryParse()를 이용한 방법
DateTime.TryParse(string, out DateTime)는 문자열을 파싱하고, out DateTime에 변환된 DateTime 객체를 할당합니다.
문자열 파싱이 성공하면 true를 리턴하며, FormatException 에러가 발생하여 실패하면 false가 리턴되며 에러는 내부에서 조용히 처리됩니다.
namespace Example {
public class Program {
public static void Main(string[] args) {
string str = "20221205";
DateTime datetime;
if (DateTime.TryParse(str, out datetime)) {
Console.WriteLine(datetime);
} else {
Console.WriteLine("Unable to parse " + str);
}
}
}
}Output:
Unable to parse 202212053. DateTime.ParseExact()로 Custom 날짜 문자열 파싱
DateTime.ParseExact(string, formats, provider)는 formats에 입력된 형식의 문자열만 파싱합니다. CultureInfo는 지역에 대한 정보를 제공합니다.
formats에 원하는 형식을 정의하여 문자열을 파싱할 수 있습니다.
using System.Globalization;
namespace Example {
public class Program {
public static void Main(string[] args) {
string[] formats = new[] {
"yyyyMMdd",
"MM/dd/yyyy HH:mm:ss"
};
CultureInfo provider = new CultureInfo("en-US");
string str = "20221205";
Console.WriteLine(DateTime.ParseExact(str, formats, provider));
str = "06/12/2022 10:20:30";
Console.WriteLine(DateTime.ParseExact(str, formats, provider));
}
}
}Output:
12/5/2022 12:00:00 AM
6/12/2022 10:20:30 AMformats에 정의되지 않은 문자열을 파싱하면 FormatException가 발생합니다.
string[] formats = new[] {
"yyyyMMdd",
"MM/dd/yyyy HH:mm:ss"
};
CultureInfo provider = new CultureInfo("en-US");
string str = "09 Dec 2022";
Console.WriteLine(DateTime.ParseExact(str, formats, provider));Output:
Unhandled exception. System.FormatException: String '09 Dec 2022' was not recognized as a valid DateTime.
at System.DateTimeParse.ParseExactMultiple(ReadOnlySpan`1 s, String[] formats, DateTimeFormatInfo dtfi, DateTimeStyles style)
at System.DateTime.ParseExact(ReadOnlySpan`1 s, String[] formats, IFormatProvider provider, DateTimeStyles style)4. DateTime.TryParseExact()으로 Custom 날짜 문자열 파싱
DateTime.TryParseExact()는 DateTime.ParseExact()와 같이 특정 형식의 문자열을 파싱하는데, FormatException가 발생하면 내부에서 예외를 처리하고 false를 리턴합니다.
using System.Globalization;
namespace Example {
public class Program {
public static void Main(string[] args) {
string[] formats = new[] {
"yyyyMMdd",
"MM/dd/yyyy HH:mm:ss"
};
CultureInfo provider = new CultureInfo("en-US");
string str = "09 Dec 2022";
DateTime datetime;
if (DateTime.TryParseExact(str, formats, provider,
DateTimeStyles.None, out datetime)) {
Console.WriteLine(datetime);
} else {
Console.WriteLine("Unable to parse " + str);
}
}
}
}Output:
Unable to parse 09 Dec 2022Loading script...
Related Posts
- C# 바이트(Byte) 배열을 문자열로 변환
- C# String.format() 함수 알아보기
- C# - foreach (Array, List, Dictionary)
- C# 프로퍼티(Property) Get/Set 함수
- C# - Dictionary에서 key, value 가져오기
- C# - Dictionary 순회, foreach, for 루프
- C# - Dictionary에서 key, value 삭제
- C# - Dictionary.add()로 데이터 추가
- C# - Dictionary 선언 및 초기화
- C# - 문자열을 Double, Float으로 변환
- C# - 문자열을 리스트로 변환
- C# - 두 날짜/시간 비교, DateTime.Compare()
- C# - 날짜 문자열을 DateTime으로 변환
- C# - Sleep, 몇 초간 지연시키기
- C# - 날짜 계산, DateTime 시간 더하기 빼기
- C# - Timestamp(millisecond)를 DateTime 객체로 변환
- C# - 현재 시간 가져오기, DateTime
- C# - 문자열 리스트를 문자열로 변환
- C# - 리스트 복사 (얕은 복사, 깊은 복사)
- C# - 2차원 리스트 선언 및 초기화
- C# - 리스트 선언 및 초기화
- C# - 리스트 길이, 크기 가져오기
- C# - 리스트 합계, 평균 계산
- C# - 리스트 요소 제거 (RemoveAt, RemoveAt, RemoveAll)
- C# - 리스트에서 빈 문자열, null 제거
- C# - 리스트 두개로 분리, n개로 나누기
- C# - 문자열 뒤집기, Reverse()
- C# - 2차원 배열 복사, Clone
- C# - 문자열 배열을 문자열로 변환
- C# - 2차원 배열 선언, 초기화 방법
- C# - 배열 길이, 2차원 배열 길이
- C# - 두개의 배열을 하나로 합치기
- C# - 배열 중복 요소 제거
- C# - 배열에서 특정 요소 제거
- C# - Int 배열 정렬 (오름차순, 내림차순)