C# 類--(Date time)

來源:互聯網
上載者:User

標籤:

輸入一個日期判斷是否正確:


Console.WriteLine(" 請按照格式正確輸入年月日(yyy/MM/dd)");
string a = Console.ReadLine();
DateTime dt = new DateTime();
dt = DateTime.Parse(a);
string s;
s = dt.ToString("yyyy年MM月dd日");
string y = s.Substring(0, 4);
string m = s.Substring(5, 2);
string d = s.Substring(8, 2);
int y1 = Convert.ToInt32(y);
int m1 = Convert.ToInt32(m);
int d1 = Convert.ToInt32(d);
int runnian = 0;
if (y1 % 4 == 0 && y1 % 100 != 0 || y1 % 400 == 0)
{
runnian = 1;
}
if (y1 > 1 && y1 <= 9999 && m1 > 0 && m1 <= 12 && d1 > 0 && d1 <= 31)
{
if (m1 == 4 || m1 == 6 || m1 == 8 || m1 == 11 && d1 > 30)
{
Console.WriteLine("輸入錯誤");
}
else if (m1 == 2 && d1 > 29)
{
Console.WriteLine("輸入錯誤");
}
else if (m1 == 2 && d1 == 29 && runnian != 1)
{
Console.WriteLine("輸入錯誤!" + y1 + "不是閏年,2月沒有29號!");
}
else
{
Console.WriteLine(s);
Console.WriteLine("輸入正確");
}

}
Console.ReadLine();

方法2:


Console.WriteLine(" 請按照格式正確輸入年月日(yyy/MM/dd)");
string a = Console.ReadLine();
try
{
DateTime dt = new DateTime();
dt = Convert.ToDateTime(a);
Console.WriteLine("輸入正確");
}
catch (Exception)
{

Console.WriteLine("輸入錯誤");
}
Console.ReadLine();

C# 類--(Date time)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.