简体   繁体   English

计算两个日期之间的天数并将其显示在标签中

[英]Calculating the Number of Days between two Dates and displaying it in a Label

Hi I'm trying to capture two dates selected by the user in a C# Calendar Control and I want the date range to be displayed in a label.嗨,我正在尝试捕获用户在 C# 日历控件中选择的两个日期,我希望日期范围显示在标签中。 I have worked out on the following code but it generates a Minus value ;我已经制定了以下代码,但它生成了一个 Minus 值; not the actual date range.不是实际的日期范围。

DateTime from = CalFrom.SelectedDate;
DateTime to = CalTo.SelectedDate;
double days = (CalTo.SelectedDate - CalFrom.SelectedDate).TotalDays;
TimeSpan t = to - from;
double noOfDays = t.TotalDays;
TimeSpan ts = to - from;
double differnceindays = ts.TotalDays;
lblNoofDays.Text = differnceindays.ToString();

This code is working perfectly for me for calculating the number the days between two days.这段代码非常适合我计算两天之间的天数。

DateTime d1 = DateTime.Now;
DateTime d2 = DateTime.Now.AddDays(10);
TimeSpan difference = d2 - d1;      
var days = difference.TotalDays;
 DateTime.Now.Subtract(startDate).Days.ToString();

try to calculate no of days between two dates尝试计算两个日期之间的天数

string days = (date2 - date1).Value.Days.ToString(); string days = (date2 - date1).Value.Days.ToString();

The only problem I see is that you assume the start and end dates will be correctly range checked, meaning start date is never greater than end date (which would produce negative values for total days).我看到的唯一问题是您假设开始日期和结束日期将被正确范围检查,这意味着开始日期永远不会大于结束日期(这会产生总天数的负值)。 If you want to correct for the fact that start date may be after end date, then this should work.如果您想纠正开始日期可能晚于结束日期的事实,那么这应该可行。

DateTime startDate = DateTime.Now.AddDays(-94); // Example random 94 day span..
DateTime endDate = DateTime.Now;
TimeSpan duration = endDate > startDate ? endDate - startDate : startDate - endDate;
double daysBetweenDates = duration.TotalDays;

Note: "daysBetweenDates" will include fractional days (thus the double type).注意:“daysBetweenDates”将包括小数天数(因此是双精度型)。 Also, the code above assumes local time.此外,上面的代码假定本地时间。 If you want UTC you will need to account for that.如果你想要UTC,你需要考虑到这一点。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM