计算日,月,年 [英] Calculating Day, Month, Year

查看:128
本文介绍了计算日,月,年的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我如何计算日,月,年到底是什么?

How do I calculate Day, Month, Year exactly?

手段..

从1月2日1990年至2009年5月9日是..

From 2th Jan 1990 to 9th May 2009 is..

XXX天,XXX月,XXX年。

xxx Days, xxx Months, xxx Years.

不知道如何要做到这一点?

Any idea how to do that?

我试过时间跨度和蜱()..双方未能如愿..

I tried Timespan and Tick().. Both failed to do so..

推荐答案

您不能做到这一点通过直接计算(即没有TotalMonths或TotalYears时间跨度的财产,仅仅是因为这些数字做,不与时间任意间隔)感。

You cannot do it through direct calculation (i.e. there's no "TotalMonths" or "TotalYears" property of TimeSpan, simply because those numbers do not make sense with arbitrary intervals of time).

相反,你可以指望在一个循环的数量,像这样:

Instead, you can just count the number in a loop, like so:

var dt1 = new DateTime(1990, 1, 2);
var dt2 = new DateTime(2009, 5, 9);

int years = 0;
while (dt1.AddYears(1) < dt2)
{
    years ++;
    dt1 = dt1.AddYears(1);
}

int months = 0;
while (dt1.AddMonths(1) < dt2)
{
    months ++;
    dt1 = dt1.AddMonths(1);
}

int days = (int) Math.Floor(dt2.Subtract(dt1).TotalDays);



我没有测试过这一点,所以有可能是关闭接一个错误或什么的,但这是最基本的想法。

I haven't tested this, so there might be off-by-one errors or whatever, but that's the basic idea.

这篇关于计算日,月,年的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆