四舍五入至最近的n个月

时间:2019-03-21 02:35:40

标签: c# datetime

我正在为DateTime结构编写一个扩展函数,将其舍入到给定的 non inclusive 粒度。例如:

Date = 11/26/18
Date.RoundMonth( 1 ); // 11/1/18 ( Rounds current month )
Date.RoundMonth( 2 ); // 11/1/18 ( Skips months 1-2, 3-4, 5-6, 7-8, 9-10 )
Date.RoundMonth( 3 ); // 10/1/18 ( Skips months 1-3, 4-6, 7-9 )
Date.RoundMonth( 4 ); // 09/1/18 ( Skips months 1-4, 5-8 )
Date.RoundMonth( 6 ); // 07/1/18 ( Skips months 1-6 )

Date = 05/11/18
Date.RoundMonth( 1 ); // 05/1/18 ( Rounds current month )
Date.RoundMonth( 2 ); // 05/1/18 ( Skips months 1-2, 3-4 )
Date.RoundMonth( 3 ); // 04/1/18 ( Skips months 1-3 )
Date.RoundMonth( 4 ); // 05/1/18 ( Skips months 1-4 )
Date.RoundMonth( 6 ); // 01/1/18 ( 5 is within 1-6 )

这是我当前的实现方式

public static DateTime RoundMonth( this DateTime date, int roundValue )
{
  var monthIndex = date.Month / roundValue * roundValue;
  return new DateTime( date.Year, monthIndex, 1, 0, 0, 0, DateTimeKind.Utc );
}

此实现存在多个问题。

  • 如果date.Month小于roundValue,则monthIndex始终为零,并且DateTime构造函数不允许索引为0。如果monthIndex大于零,则它包括上一个期间的最后一个月(而我上面的示例中没有)。

  • 如果在monthIndex的末尾添加1,则可以工作,但是月份为12,则DateTime构造函数将引发异常,因为计算的月份为13。如果monthIndex为1,不正确地增加到2。

如果没有麻烦的算术语句,if语句和对Math.Min的调用,我想不出解决这些问题的方法。我一定想念一些明显的东西...

值得一提的是,此函数将被称为很多(用于将日期排序到存储桶中),因此性能有些令人担忧。

0 个答案:

没有答案