C#将日期舍入到一个月的10日、20日或30日
c#
DateTime 中是否有一种方便的方法可以将 DateTime 中的给定日期四舍五入到最近的 10 日、20 日或 30 日,还是我必须自己计算?例如,4 月 12 日变为 20 日,4 月 3 日变为 10 日,依此类推。
回答
没有内置功能。
该代码将取决于每月最后十天之后的所需行为,例如 2 月 26 日或 5 月 31 日。
这里有2个版本。
如果您决定 31 日是 5 月 10 日,请确保处理 12 月,您必须更改年份。
版本 1
// This looses milliseconds
var day = d.Month == 2
? (d.Day > 10 ? 20 : 10)
: (d.Day > 20 ? 30 : (d.Day > 10 ? 20 : 10));
var d2 = new DateTime(d.Year, d.Month, day, d.Hour, d.Minute, d.Second, d.Kind);
测试
21/02/2021 -> 20/02/2021
31/05/2021 -> 30/05/2021
1/04/2021 -> 10/04/2021
2/04/2021 -> 10/04/2021
3/04/2021 -> 10/04/2021
4/04/2021 -> 10/04/2021
5/04/2021 -> 10/04/2021
6/04/2021 -> 10/04/2021
7/04/2021 -> 10/04/2021
8/04/2021 -> 10/04/2021
9/04/2021 -> 10/04/2021
10/04/2021 -> 10/04/2021
11/04/2021 -> 20/04/2021
12/04/2021 -> 20/04/2021
13/04/2021 -> 20/04/2021
14/04/2021 -> 20/04/2021
15/04/2021 -> 20/04/2021
16/04/2021 -> 20/04/2021
17/04/2021 -> 20/04/2021
18/04/2021 -> 20/04/2021
19/04/2021 -> 20/04/2021
20/04/2021 -> 20/04/2021
21/04/2021 -> 30/04/2021
22/04/2021 -> 30/04/2021
23/04/2021 -> 30/04/2021
24/04/2021 -> 30/04/2021
25/04/2021 -> 30/04/2021
26/04/2021 -> 30/04/2021
27/04/2021 -> 30/04/2021
28/04/2021 -> 30/04/2021
29/04/2021 -> 30/04/2021
30/04/2021 -> 30/04/2021
版本 2
var daysInMonth = DateTime.DaysInMonth(d.Year, d.Month);
var dayCandidate = ((d.Day + 9) / 10) * 10;
var day = dayCandidate <= daysInMonth ? dayCandidate : ((daysInMonth / 10) * 10);
// This looses milliseconds
var d2 = new DateTime(d.Year, d.Month, day, d.Hour, d.Minute, d.Second, d.Kind);
测试选择:
28/02/2021 -> 20/02/2021
31/05/2021 -> 30/05/2021
1/04/2021 -> 10/04/2021
2/04/2021 -> 10/04/2021
9/04/2021 -> 10/04/2021
10/04/2021 -> 10/04/2021
11/04/2021 -> 20/04/2021
19/04/2021 -> 20/04/2021
20/04/2021 -> 20/04/2021
21/04/2021 -> 30/04/2021
29/04/2021 -> 30/04/2021
30/04/2021 -> 30/04/2021