車輪を再発明しないでくださいDateTime.TryParseExact
。この目的のために特別に構築された方法を使用してください。.NET フレームワークで日付を扱うときは、正規表現と部分文字列を忘れてください。
public static bool CheckDate(string number, out DateTime date)
{
return DateTime.TryParseExact(number, "dd/MM/yyyy", CultureInfo.InvariantCulture, DateTimeStyles.None, out date);
}
ご覧のとおり、CheckDate
は既に BCL に存在するため、 を定義しても意味がありません。次のように簡単に使用できます。
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
}
アップデート:
コメント セクションで、実際には質問に答えていないという発言を受け取ったので、私が推奨するアプローチと同様のアプローチを使用できます。ただし、TryXXX パターンを説明するためだけに、このようなコードを書くことは絶対にないと約束してください。
モデルを定義します。
public class Patterns
{
public string DD { get; set; }
public string MM { get; set; }
public string YYYY { get; set; }
}
次に、CheckDate メソッドを変更して、out パラメーターを送信するようにします。
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
}