- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Text.RegularExpressions;
- namespace test5
- {
- class Program
- {
- //得到字符串中的年
- static int GetYear(string str)
- {
- List<int> list = new List<int>();
- MatchCollection match1 = Regex.Matches(str, @"\d+");
- foreach (Match item in match1)
- {
- list.Add(Convert.ToInt32(item.Value));
- }
- return list[0];
- }
- //得到字符串中的月
- static int GetMonth(string str)
- {
- List<int> list = new List<int>();
- MatchCollection match1 = Regex.Matches(str, @"\d+");
- foreach (Match item in match1)
- {
- list.Add(Convert.ToInt32(item.Value));
- }
- return list[1];
- }
- //得到字符串中的天
- static int GetDay(string str)
- {
- List<int> list = new List<int>();
- MatchCollection match1 = Regex.Matches(str, @"\d+");
- foreach (Match item in match1)
- {
- list.Add(Convert.ToInt32(item.Value));
- }
- return list[2];
- }
- //判断是否是闰年
- static bool IsYear(int num)
- {
- if (num % 400 == 0 || (num % 4 == 0 && num % 100 != 0))
- {
- return true;
- }
- return false;
- }
- //得到当前年份的天数
- static int Days(int year, int month, int day)
- {
- bool flag = IsYear(year);
- int days = day;
- for (int i = 1; i <= month; i++)
- {
- switch (i-1)
- {
- case 1:
- case 3:
- case 5:
- case 7:
- case 8:
- case 10:
- case 12:
- days = days + 31;
- break;
- case 4:
- case 6:
- case 9:
- case 11:
- days = days + 30;
- break;
- case 2:
- if (flag == true)
- {
- days = days + 29;
- }
- days = days + 28;
- break;
- }
- }
- return days;
- }
- static void Main(string[] args)
- {
- string str1 = "1999年5月10日";
- string str2 = "2006年3月8日";
- int days=0;
- int startYear = GetYear(str1);
- int endYear = GetYear(str2);
- //得到年份之间的天数
- for (var i = startYear+1; i < endYear; i++)
- {
- bool flag = IsYear(i);
- if (flag == true)
- {
- days = days + 365;
- }
- else
- {
- days = days + 366;
- }
- }
- days =days+ Days(GetYear(str2), GetMonth(str2), GetDay(str2)) - Days(GetYear(str1), GetMonth(str1), GetDay(str1));
- Console.WriteLine("{0}到{1}之间一共有{2}天",str1,str2,days);
- Console.ReadKey();
- }
- }
- }
复制代码 |