黑马程序员技术交流社区
标题:
求解最简洁的方式判断成年,要求精确到生日
[打印本页]
作者:
覃庆健
时间:
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
试试这个
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace test2
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("请输入您的生日(比如1990-1-1)");
string strDate = Console.ReadLine();
bool is_adult = isAdult(strDate);
if (is_adult == true)
{
Console.WriteLine("已成年");
}
else Console.WriteLine("未成年");
Console.Read();
}
static bool isAdult(string date)
{
string[] strYear = date.Split('-');
int year = int.Parse(strYear[0]);
int month = int.Parse(strYear[1]);
int day = int.Parse(strYear[2]);
DateTime dt = DateTime.Now;
int currentYear = dt.Year;
int currentMonth = dt.Month;
int currentDay = dt.Day;
if (currentYear - year >= 18)
{
if (currentMonth > month)
{
return true;
}
else if (currentMonth == month)
{
if (currentDay >= day) return true;
}
}
return false;
}
}
}
复制代码
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2