如何天数转换为年,月,日 [英] How to convert number of days to years,months and days

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

问题描述

如果我有两个日期,然后我让他们之间的区别在天像这个帖子

If i have Two dates then i get the difference between them in days Like this Post.

如何的细节,在以下几种观点:

How to detail that in the following view :

转换的日子(的年数,月数和休息天数

推荐答案

有没有开箱即用的解决方案这一点。问题是,你正在处理的变量的数据即不是所有年份365天,闰年就变成366。此外,不是每个月都可以被认为是标准的30天。

There is no "out of the box" solution for this. The problem is you are dealing with variable data i.e. not all years are 365 days, on a leap year it becomes 366. Furthermore, not every month can be assumed to be standard 30 days.

这是非常难以计算这类信息,没有背景 - 你有时间的日子,然而,来计算(至少准确)的年/月,你需要的上下文的数量。例如,你需要知道哪些特定的月份和它特殊的一年,你正在处理以确定年份是否是闰年,或者特定的月份是30/31天,依此类推......

It's very difficult to calculate this sort of information with no context - you have a duration in days, however, to calculate (at least accurately) the number of years/months you need context. For example, you need to know which particular month and which particular year you are dealing with to determine whether that year was a leap year or if that particular month was 30/31 days and so on...

  • 1年= 365天
  • 1个月= 30天

那么下面code将完成这项工作。

Then the following code would do the job

DateTime startDate = new DateTime(2010, 1, 1);
DateTime endDate = new DateTime(2013, 1, 10);
var totalDays = (endDate - startDate).TotalDays;
var totalYears = Math.Truncate(totalDays / 365);
var totalMonths = Math.Truncate((totalDays % 365) / 30);
var remainingDays = Math.Truncate((totalDays % 365) % 30);
Console.WriteLine("Estimated duration is {0} year(s), {1} month(s) and {2} day(s)", totalYears, totalMonths, remainingDays);

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

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