如何计算C#中两个datetimepicker之间的月份 [英] How to calculate months between two datetimepicker in C#

查看:395
本文介绍了如何计算C#中两个datetimepicker之间的月份的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Good day everyone please i want to calculate months differences between two date time picker. And i want it to give me an error if it more than one year. the code here is for if the dates choosen has not expired

What I have tried:

<pre>DateTime reqdt = dtrequest.Value.Date;
DateTime retdt = dtreturn.Value.Date;

TimeSpan ts = retdt - reqdt;
int days = ts.Days;
if (days <= 0)
{
MessageBox.Show("Date Expired");
}
else
{
MessageBox.Show("better");

lbldiff.Text = days.ToString() + "Days";

推荐答案

//The trick here is to use the AddYears method
DateTime firstDate = DateTime.Now;
DateTime secondDate= firstDate.AddDays(367);
DateTime expiryDate = firstDate.AddYears(1);
string msg = secondDate > expiryDate ? "Expired" : "Not Expired";
Console.WriteLine(msg);


Quote:

我想计算两个日期时间之间的月份差异

i want to calculate months differences between two date time



你基本上有2个解决方案:

- 或者你说一个月大约是31.5天并且使用计算的天数。

- 您可以通过处理两个日期的年,月和日来自行计算。

它看起来像:


You basically have 2 solutions:
- Either you say that a month is roughly 31.5 days and use the number of days for the calculation.
- Either you do the calculation yourself by handling years, months and days of both dates.
it will look like:

NbMonths= ( retdt.year - reqdt.year ) * 12 + ( retdt.month - reqdt.month )
if ( retdt.day < reqdt.day ) {
  NbMonths--
}


如果您需要更准确的计算,将国际化(文化/日历)考虑在内,CodeProject有一篇优秀的文章/代码 - Jani Giannoudis的图书馆:[ ^ ]。现在正在GitHub上开发,并针对.NET Core,Mono,Xamarin和UWP进行了更新。



您可以检查'DateDiff类中的(复杂)代码看看总月数是如何计算的。



另一个用于日期/时间计算的全功能C#库是Jon Skeet的'NodaTime:[ ^ ] ...在GitHub上:[ ^ ]
If you need a more accurate calculation, that takes internationalization (Culture/Calendar) into account, CodeProject has an excellent article/code-library by Jani Giannoudis: [^]. This is being developed on GitHub now, and updated for .NET Core, Mono, Xamarin and UWP.

You can examine the (complex) code in the 'DateDiff class to see how total months are calculated.

Another full featured C# library for Date/Time calculations is Jon Skeet's 'NodaTime: [^] ... on GitHub: [^]


这篇关于如何计算C#中两个datetimepicker之间的月份的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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