바퀴를 다시 열지 마십시오.이 목적으로 특별히 제작 된 DateTime.TryParseExact
방법을 사용하십시오.
public static bool CheckDate(string number, out DateTime date)
{
return DateTime.TryParseExact(number, "dd/MM/yyyy", CultureInfo.InvariantCulture, DateTimeStyles.None, out date);
}
을 그리고 당신은 정의 볼 수는 이미 BCL에 존재하기 때문에 지금 CheckDate
좀 의미가됩니다 : 당신은 .NET 프레임 워크에서 날짜를 처리 할 때 정규 표현식에와 문자열 잊어 버려요. 당신은 단순히 다음과 같이 사용합니다 :
이
string number = "that's your number coming from somewhere which should be a date";
DateTime date;
if (DateTime.TryParseExact(
number,
"dd/MM/yyyy",
CultureInfo.InvariantCulture,
DateTimeStyles.None,
out date
))
{
// the number was in the correct format
// => you could use the days, months, from the date variable which is now a DateTime
string dd = date.Day.ToString();
string mm = date.Month.ToString();
string yyyy = date.Year.ToString();
// do whatever you intended to do with those 3 variables before
}
else
{
// tell the user to enter a correct date in the format dd/MM/yyyy
}
UPDATE : 나는 실제로 질문에 대답하고 있지 않다 코멘트 섹션에서 발언을 가지고 있기 때문에
, 당신은 유사한 접근 방법을 사용할 수 있습니다 하나는 내가 권 해드립니다. 하지만 제발, 과 같은 코드를 쓰지 않겠다고 약속 해주세요.은 TryXXX 패턴을 보여주기위한 것입니다.
는 모델 정의
public static bool CheckDate(string number, out Patterns patterns)
{
patterns = null;
string new_number = number.ToString();
if (new_number.Length == 8)
{
Patterns = new Patterns
{
YYYY = new_number.Substring(0, 4),
MM = new_number.Substring(4, 2),
DD = new_number.Substring(6, 2)
}
return true;
}
else
{
return false;
}
}
이 같이 사용할 수 있습니다 :
string number = "that's your number coming from somewhere which should be a date";
Patterns patterns;
if (CheckDate(numbers, out patterns)
{
string dd = patterns.DD;
string mm = patterns.MM;
string yyyy = patterns.YYYY;
// do whatever you intended to do with those 3 variables before
}
else
{
// tell the user to enter a correct date in the format dd/MM/yyyy
}
질문에 더 의미있는 제목을 선택하십시오. –
예, 보낼 수 있습니다. CheckDate에서 여러 값을 반환하는 것에 대해 묻고 있습니까? – ryadavilli