在c#中获取基于天数的月数

本文关键字:于天数 获取 | 更新日期: 2023-09-27 18:03:57

我一直在努力弄清楚这个…

我们目前在我们的报告上有一个日期标准,按天限制,当然可以配置,目前设置为90天。消息说,它是90天的限制,然而我的老板想增加到13个月,不幸的是,如果我这样做,我需要做的天,它会说,395天..

不是一个很友好的消息…

试图找出一种方法来满足这一点,我的另一个唯一的选择是添加另一个受月和天限制的设置。但是我仍然需要将月份转换回天数,这并不完美,因为不是每个月都有相同的日子。

想法?

在c#中获取基于天数的月数

您需要决定是使用13个月作为时间间隔,还是使用接近13个月的天数。如果使用13个月,则天数(或报告的结束日期)将根据开始日期而变化。

我建议让您的报告可配置为月或天(不仅存储数字,而且存储配置中的单位)。然后,您可以在报告中显示配置中指定的任何内容(以及来自配置的单位),并通过将配置的单位的配置数量添加到开始日期来计算查询的结束日期。

如果你想在几天内完成所有的事情,当你现在需要几个月的工作时,你只会让自己的生活变得困难。

在开始日期加上13个月来得到结束日期要比尝试(不准确地)计算给定天数中有多少个月容易得多。

使用TimeSpan对象执行日期标准所需的计算。

如果给定天数,我会这样做:

int myDays;   // 390 or whatever
DateTime d1 = DateTime.Now;
DateTime d2 = d1.AddDays(myDays);
int monthsDiff = d2.Month - d1.Month + 12 * (d2.Year - d1.Year);
DateTime d3 = d1.AddMonths(monthsDiff);
TimeSpan tf = d2 - d3;
string msg = monthsDiff.ToString() + " months, " + tf.Days + " days";

TimeSpan给出两个DateTime对象之间的持续时间。它可以持续地以天、小时或分钟为单位;月数会根据实际开始时间而有所不同。不同月份的结束日期有不同的实际天数

话虽如此,你总是可以写一个实用程序方法,给你YourTimeSpan对象,根据你的日历和开始日期/结束日期给你的月数等。

在您的情况下,您可以通过在配置中单独存储它来使它更简单,例如- ReportDuration_Years, ReportDuration_Months, ReportDuration_Days。这将允许您在报表上创建有意义的标签,以及允许正确识别StartDate和EndDate。

//Call this by passing values from configuration
private string GetNiceLookingLable(int? years, int? months, int? days){
    var yearMessage = (years.HasValue)?String.Format("{0} Years", years):String.Empty;
    var monthMessage = (months.HasValue)?String.Format("{0} Months", months):String.Empty;
    var daysMessage = (days.HasValue)?String.Format("{0} Days", days):String.Empty;
    // You probably want to concatenate them properly
    return String.Format("{0} {1} {2}",yearMessage, monthMessage, daysMessage);
}

//Call this to get starting date
private DateTime getStartingDate(int? years, int? months,int? days){
     var retDate = DateTime.Today;
     if(years.HasValue){
         retDate = retDate.AddYears(-1*years.Value);
     }
     if(months.HasValue){
         retDate = retDate.AddMonths(-1*months.Value);
     }
     if(days.HasValue){
         retDate = retDate.AddDays(-1*days.Value);
     }
     return retDate;
}