날짜가 yyyy-dd-MM 형식 인 DateTime.TryParse 문제
다음 날짜는 문자열 형식 "2011-29-01 12:00 am"입니다. 이제 다음 코드를 사용하여이를 datetime 형식으로 변환하려고합니다.
DateTime.TryParse(dateTime, out dt);
하지만 나는 항상 dt를 {1/1/0001 12:00:00 AM}으로 받고 있습니다. 이유를 말씀해 주시겠습니까? 그 문자열을 날짜로 어떻게 변환 할 수 있습니까?
편집 : 나는 모두가 형식 인수를 사용하도록 언급하는 것을 보았습니다. 사용자가 원하는 사용자 지정 날짜 형식을 선택하는 일부 설정이 있고 해당 사용자를 기반으로 jQuery datepicker를 통해 해당 형식의 텍스트 상자에서 날짜를 자동으로 가져올 수 있으므로 format 매개 변수를 사용할 수 없다는 점을 이제 언급하겠습니다.
이것은 "2011-29-01 12:00 am"예제를 기반으로 작동합니다.
DateTime dt;
DateTime.TryParseExact(dateTime,
"yyyy-dd-MM hh:mm tt",
CultureInfo.InvariantCulture,
DateTimeStyles.None,
out dt);
ParseExact방법 을 사용해야합니다 . 이것은 datetime의 형식을 지정하는 두 번째 인수로 문자열을 취합니다. 예를 들면 다음과 같습니다.
// Parse date and time with custom specifier.
dateString = "2011-29-01 12:00 am";
format = "yyyy-dd-MM h:mm tt";
try
{
result = DateTime.ParseExact(dateString, format, provider);
Console.WriteLine("{0} converts to {1}.", dateString, result.ToString());
}
catch (FormatException)
{
Console.WriteLine("{0} is not in the correct format.", dateString);
}
사용자가 UI에서 형식을 지정할 수있는 경우이 형식을이 메서드에 전달할 수있는 문자열로 변환해야합니다. 사용자가 형식 문자열을 직접 입력하도록 허용하면 됩니다. 이는 잘못된 형식 문자열을 입력하기 때문에 변환이 실패 할 가능성이 더 높다는 것을 의미 하거나 가능한 선택 사항을 제공하는 콤보 상자를 사용하여 수행 할 수 있습니다. 이러한 선택에 대한 형식 문자열을 설정합니다.
입력이 올바르지 않을 가능성이있는 경우 (예 : 사용자 입력) TryParseExact오류 사례를 처리하기 위해 예외를 사용 하는 것보다 사용 하는 것이 좋습니다.
// Parse date and time with custom specifier.
dateString = "2011-29-01 12:00 am";
format = "yyyy-dd-MM h:mm tt";
DateTime result;
if (DateTime.TryParseExact(dateString, format, provider, DateTimeStyles.None, out result))
{
Console.WriteLine("{0} converts to {1}.", dateString, result.ToString());
}
else
{
Console.WriteLine("{0} is not in the correct format.", dateString);
}
더 나은 대안은 사용자에게 날짜 형식을 선택 하지 않고 형식 배열을 사용하는 오버로드를 사용하는 것입니다 .
// A list of possible American date formats - swap M and d for European formats
string[] formats= {"M/d/yyyy h:mm:ss tt", "M/d/yyyy h:mm tt",
"MM/dd/yyyy hh:mm:ss", "M/d/yyyy h:mm:ss",
"M/d/yyyy hh:mm tt", "M/d/yyyy hh tt",
"M/d/yyyy h:mm", "M/d/yyyy h:mm",
"MM/dd/yyyy hh:mm", "M/dd/yyyy hh:mm",
"MM/d/yyyy HH:mm:ss.ffffff" };
string dateString; // The string the date gets read into
try
{
dateValue = DateTime.ParseExact(dateString, formats,
new CultureInfo("en-US"),
DateTimeStyles.None);
Console.WriteLine("Converted '{0}' to {1}.", dateString, dateValue);
}
catch (FormatException)
{
Console.WriteLine("Unable to convert '{0}' to a date.", dateString);
}
구성 파일이나 데이터베이스에서 가능한 형식을 읽으면 사람들이 날짜를 입력하려는 모든 다른 방법을 만나면서 여기에 추가 할 수 있습니다.
에서 날짜 시간 MSDN의 :
형식 : System.DateTime %이 메서드가 반환 될 때 s에 포함 된 날짜 및 시간 (변환에 성공한 경우) 또는 MinValue (변환에 실패한 경우)에 해당하는 DateTime 값을 포함합니다 . s 매개 변수가 null이거나 빈 문자열 ( "")이거나 날짜 및 시간의 유효한 문자열 표현이 포함되지 않은 경우 변환이 실패합니다. 이 매개 변수는 초기화되지 않은 상태로 전달됩니다.
Use parseexact with the format string "yyyy-dd-MM hh:mm tt" instead.
Try using safe TryParseExact method
DateTime temp;
string date = "2011-29-01 12:00 am";
DateTime.TryParseExact(date, "yyyy-dd-MM hh:mm tt", CultureInfo.InvariantCulture, DateTimeStyles.None, out temp);
That works:
DateTime dt = DateTime.ParseExact("2011-29-01 12:00 am", "yyyy-dd-MM hh:mm tt", System.Globalization.CultureInfo.InvariantCulture);
DateTime dt = DateTime.ParseExact("11-22-2012 12:00 am", "MM-dd-yyyy hh:mm tt", System.Globalization.CultureInfo.InvariantCulture);
If you give the user the opportunity to change the date/time format, then you'll have to create a corresponding format string to use for parsing. If you know the possible date formats (i.e. the user has to select from a list), then this is much easier because you can create those format strings at compile time.
If you let the user do free-format design of the date/time format, then you'll have to create the corresponding DateTime format strings at runtime.
참고URL : https://stackoverflow.com/questions/4718960/datetime-tryparse-issue-with-dates-of-yyyy-dd-mm-format
'program story' 카테고리의 다른 글
| 텍스트가 일관성없이 렌더링되고 일부 글꼴이 다른 글꼴보다 큰 모바일 Safari (iPhone)의 글꼴 크기 문제를 해결합니까? (0) | 2020.10.31 |
|---|---|
| while 루프를 사용하는 것보다 파이썬에서 range ()를 반복하는 것이 왜 더 빠릅니까? (0) | 2020.10.31 |
| Elasticsearch 2.0에서 원격 액세스 / 요청을 활성화하려면 어떻게해야합니까? (0) | 2020.10.31 |
| 쉘 스크립트에서 기간을 초 단위로 측정하려면 어떻게합니까? (0) | 2020.10.31 |
| 내 ASP.NET Web API ActionFilterAttribute OnActionExecuting이 실행되지 않는 이유는 무엇입니까? (0) | 2020.10.31 |