黑马程序员技术交流社区

标题: 求解最简洁的方式判断成年,要求精确到生日 [打印本页]

作者: 覃庆健    时间: 2013-4-13 21:57
标题: 求解最简洁的方式判断成年,要求精确到生日
本帖最后由 覃庆健 于 2013-4-20 06:00 编辑

例如 生日是1995-05-05, 今天是2013-04-13
我想用2013-04-13减去1995-05-05,来判断是否成年
怎么做。
要求精确到年月日..如2013-1995等于18这个不算,
还有大半月才成年呢
另,有没有能直接调用的方法呢(年月日直接相加减的)。
作者: Asan    时间: 2013-4-13 22:18
我觉得写三个if语句应该就可以了!
作者: 张正强    时间: 2013-4-13 23:38
DateTime dt = new DateTime(1995,04,14);
TimeSpan ts =DateTime.Now-dt;
Console.WriteLine(ts.Days/365);//因为没有提供ts.Years属性,所以这个计算比较笼统,没有考虑闰年
作者: 韦俊琳    时间: 2013-4-14 01:29
试试这个
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;

  5. namespace test2
  6. {
  7.     class Program
  8.     {

  9.         static void Main(string[] args)
  10.         {
  11.             
  12.                 Console.WriteLine("请输入您的生日(比如1990-1-1)");
  13.                 string strDate = Console.ReadLine();
  14.                 bool is_adult = isAdult(strDate);
  15.                 if (is_adult == true)
  16.                 {
  17.                     Console.WriteLine("已成年");
  18.                 }
  19.                 else Console.WriteLine("未成年");
  20.             
  21.             Console.Read();
  22.         }
  23.         static bool isAdult(string date)
  24.         {
  25.             string[] strYear = date.Split('-');
  26.             int year = int.Parse(strYear[0]);
  27.             int month = int.Parse(strYear[1]);
  28.             int day = int.Parse(strYear[2]);
  29.             DateTime dt = DateTime.Now;
  30.             int currentYear = dt.Year;
  31.             int currentMonth = dt.Month;
  32.             int currentDay = dt.Day;
  33.             if (currentYear - year >= 18)
  34.             {
  35.                 if (currentMonth > month)
  36.                 {
  37.                     return true;
  38.                 }
  39.                 else if (currentMonth == month)
  40.                 {
  41.                     if (currentDay >= day) return true;
  42.                 }

  43.             }
  44.             
  45.                 return false;
  46.            
  47.         }

  48.       }
  49.     }

复制代码





欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2