日期:2014-05-17 浏览次数:20948 次
using System; using System.Collections.Generic; using System.Text; namespace IDprocess { class Program { static void Main(string[] args) { Console.Write("请输入身份证号:"); string idnumber = Console.ReadLine().Trim(); ID oneID = new ID(idnumber); if (oneID.IsValid()) Console.WriteLine("您的出生日期是:" + oneID.getBirthday().ToString("yyyy年M月d日")); else Console.WriteLine("对不起,身份证号码错误!"); Console.Read(); } } class ID { private string IDnumber; public ID(string idnumber) { this.IDnumber = idnumber.Trim(); } //判断是否为有效的身份证号码: public bool IsValid() { int year, month,day ; if (IDnumber.Length == 15) { for (int i = 0; i < 15; i++) { //如果有非数字,则无效,返回false if (!char.IsNumber(IDnumber[i])) { return false; } } //取得出生年月日: year = Int32.Parse("19" + IDnumber.Substring(6, 2)); month = Int32.Parse(IDnumber.Substring(8, 2)); day = Int32.Parse(IDnumber.Substring(10, 2)); //调用方法IsValidBirthday判断是否为有效的出生年月日: return IsValidBirthday(year, month, day); } else if (IDnumber.Length == 18) { for (int i = 0; i < 17; i++) { if (!char.IsNumber(IDnumber[i])) { return false; } } if (!char.IsNumber(IDnumber[17]) && IDnumber[17] != 'X') return false; //取得出生年月日: year = Int32.Parse(IDnumber.Substring(6,4)); month = Int32.Parse(IDnumber.Substring(10, 2)); day = Int32.Parse(IDnumber.Substring(12, 2)); //调用方法IsValidBirthday判断是否为有效的出生年月日: return IsValidBirthday(year, month, day); } else return false; } //判断是否为有效的出生年月日: private bool IsValidBirthday(int year,int month,int day) { if(year==0) return false; if (month<1||month > 12) return false; //判断天数是否在指定年和月中所限制的天数范围之内。 if (day < 1 || day > DateTime.DaysInMonth(year, month)) return false; //判断出生日期是否大于现在的日期。 DateTime Birthday = new DateTime(year, month, day); if (Birthday > DateTime.Now) return false; return true; } //获取出生日期 public DateTime getBirthday() { DateTime Birthday; int year, month,day ; if (IsValid()) { if (IDnumber.Length == 15) { year = Int32.Parse("19" + IDnumber.Substring(6, 2)); month = Int32.Parse(IDnumber.Substring(8, 2)); day = Int32.Parse(IDnumber.Substring(10, 2)); Birthday = new DateTime(year, month, day); } else { year = Int32.Parse(IDnumber.Substring(6, 4)); month = Int32.Parse(IDnumber.Substring(10, 2)); day = Int32.Parse(IDnumber.Substring(12, 2)); Birthday = new DateTime(year, month, day); } } else Birthday = new DateTime(1, 1, 1); return Birthday; } } }