如何在asp.net中将年份转换为日期 [英] How to Convert Years to Day in asp .net

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

问题描述

我想转换年份i:5年到包括闰年的天数

I want to convert years i:e 5 years to how many days including leap year

推荐答案

问题是你不能这样做:5年可能包括一年,两年或零闰年,具体取决于它们所涵盖的具体年份(闰年计算的更正意味着我们每个世纪都会跳过闰日,除非它也是千禧年结束)



如果您知道开始年份(或最好是开始日期),您可以轻松获得天数:



The problem is that you can't do that: 5 years may include one, two, or zero leap years depending on the specific years that they cover (there are corrections to leap year calculations which mean we skip a leap day every century, unless it's a millennium end as well)

If you know the start year (or preferably the start date) you can easily get the number of days:

DateTime start = new DateTime(2001,1,1);
DateTime end = start.AddYears(5);
int days = (end - start).Days;


这是想法:使用以下构造函数获取两个日期,第一个和最后一个: https: //msdn.microsoft.com/en-us/library/xcfzdy4x%28v=vs.110%29.aspx



然后减去最后一个首先使用' - '运算符。此运算符返回 System.TimeSpan 类型的对象:

https://msdn.microsoft.com/en-us/library/system.timespan%28v=vs.110%29.aspx



现在,您只需要以天为单位表示时间跨度。例如: https://msdn.microsoft.com /en-us/library/system.timespan.days%28v=vs.110%29.aspx



这就是全部。选择日期时要仔细考虑;犯1天的错误很容易。如您所见,整个代码只有3行左右。



-SA
Here is the idea: take two dates, first and last, using this constructor: https://msdn.microsoft.com/en-us/library/xcfzdy4x%28v=vs.110%29.aspx.

Then subtract last from first using '-' operator. This operator returns the object of the type System.TimeSpan:
https://msdn.microsoft.com/en-us/library/system.timespan%28v=vs.110%29.aspx.

Now, you just need to express the time span in days. For example: https://msdn.microsoft.com/en-us/library/system.timespan.days%28v=vs.110%29.aspx.

That's all. Think carefully when you choose the dates; it's quite easy to make a mistake of 1 day. As you can see, the whole code will be just 3 lines or so.

—SA


这篇关于如何在asp.net中将年份转换为日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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