我正在做一个大学项目,它是年鉴项目。我需要以 yyyy/yyyy 的确切格式输入年份(例如 2020/2021),谁能帮我解析和验证?
答案 0 :(得分:0)
bool CheckDateYear(string s)
{
string s1 = s.Split('/')[0];//s.Split('-')[0]
string s2 = s.Split('/')[1];
if (DateTime.Now.Year.ToString() != s2 || (DateTime.Now.Year - 1).ToString() != s1)
return false;
else
return true;
}
...
if(CheckDateYear("2020/2021")
{
...
}
答案 1 :(得分:-1)
您可以使用正则表达式来验证:
using System;
using System.Text.RegularExpressions;
public class Example
{
public static void Main()
{
string[] values= { "2020/2021", "2019-2020",
"199e-2000" };
Regex rgx = new Regex(@"^\d{4}(/\d{4})"); // 4 digits, forward slash, 4 digits
foreach (string value in values)
Console.WriteLine("{0} {1} a valid entry.",
value,
rgx.IsMatch(value) ? "is" : "is not");
}
}
// The example displays the following output:
// 2020/2021 is a valid entry.
// 2019-2020 is not a valid entry.
// 199e-2000 is not a valid entry.