c# 计算两个时间的差值

2024-12-19 17:11:28
推荐回答(5个)
回答1:

public string getTimeSpan(DateTime startTime, DateTime endTime)
{
TimeSpan ts = endTime - startTime;
int tYear = endTime.Year-startTime.Year-((startTime.Month>endTime.Month)?1:0);
int tMonth = endTime.Year * 12 + endTime.Month - startTime.Year * 12 - startTime.Month;
int tDay = (endTime.Day>startTime.Day)?(endTime.Day-startTime.Day):(30+endTime.Day-startTime.Day);//不完善,可以改进。。。
return tYear.toString()+"年"+tMonth.toString()+"月"+ tDay+"天";
}

回答2:

DateTime now = DateTime.Now;
DateTime start = now.AddDays(2000);
TimeSpan TimeSpan = new TimeSpan();
TimeSpan = start - now;

然后你来分析有多些天,365天为一年!

另一种方法就是,你直接对年进行计算,对月进行计算,然后再对天进行计算,然组合年月日!

回答3:

我觉得该把两个时间以一个时间为基准来求两个时间的差,至于Y年M月D日可以用string。format()这个函数就可以了,具体你查下msdn

回答4:

DateTime dt1 = Convert.ToDateTime("2001-5-3");
DateTime dt2 = Convert.ToDateTime("1995-3-15");
TimeSpan dt3 = dt1.Subtract(dt2);
Console.WriteLine(dt3.Days.ToString());

回答5:

TimeSpan结构体
http://msdn.microsoft.com/zh-CN/library/system.timespan(v=VS.80).aspx

Sample:
DateTime dt1 = Convert.ToDateTime("2001-5-3");
DateTime dt2 = Convert.ToDateTime("1995-3-15");
TimeSpan ts = dt1 - dt2;
Console.WriteLine(ts.Days.ToString());

int nDays = 0;
int nMonthes = 0;
int nYears =0;

nDays = dt1.Day - dt2.Day;
nMonthes = dt1.Month - dt2.Month - (nDays < 0 ? 1 : 0);
nYears = dt1.Year - dt2.Year - (nMonthes < 0 ? 1 : 0);
if (nDays < 0)
{
nDays = dt1.AddDays(nDays).Day;
}
if (nMonthes < 0)
{
nDays = dt1.AddMonths(nMonthes).Month;
}
//月的算法有点微妙,各个月的天数不尽相同,这个只是按照最后一个月来算,比较符合实际
Console.WriteLine(nYears.ToString() + "年" + nMonthes.ToString() + "月" + nDays.ToString() + "日");