gpt4 book ai didi

c# - 使用 NodaTime 舍入时间

转载 作者:行者123 更新时间:2023-12-04 20:01:11 25 4
gpt4 key购买 nike

我有一些 LocalDateTime s,我需要根据定义的分钟列表将一天中的时间向上/向下舍入到最接近的分钟数。
例如,如果我有日期时间 2018-03-20T12:13:47 并且我必须将它舍入到下一个半小时(所以分钟是 00 或 30),我会得到 2018-03-20T12:30:00 。四舍五入将给出 2018-03-20T12:00:00

四舍五入可以是任意分钟,例如每 10 分钟 (0, 10, 20, 30, 40, 50),每一刻钟 (0, 15, 30, 45) 或说到 (15, 45) 或之后的一刻钟。这意味着四舍五入的日期可能会在另一个日期结束。

NodaTime 中是否有任何功能可以帮助进行此四舍五入,还是我必须自己编写?我现在有一个工作版本,但它包括双循环和向午夜添加小时和分钟。

最佳答案

有一种功能会有所帮助:“调整器”的想法。如果您编写自己的返回 Func<LocalTime, LocalTime> 的方法,您可以使用 LocalTime 方法将其应用于 LocalDateTimeOffsetDateTimeOffsetTimeWith (在 2.3+ 中)。

这将非常容易地帮助截断案例:

using System;
using NodaTime;

class Test
{
static void Main()
{
var truncator = CreateTruncator(10);
var start = new LocalDateTime(2018, 3, 21, 7, 32, 15);
var truncated = start.With(truncator);
Console.WriteLine(truncated); // 2018-03-21T07:30:00
}

static Func<LocalTime, LocalTime> CreateTruncator(int minuteGranularity) =>
input => new LocalTime(
input.Hour,
input.Minute / minuteGranularity * minuteGranularity);
}

(请注意,如果您将 minuteGranularity 设为 7 或其他不是 60 的因数,它仍将截断为始终从小时开始的时间段。)

但是,没有办法提前日期。调整器机制也适用于 Func<LocalDateTime, LocalDateTime> - 您可以将其应用于 LocalDateTimeOffsetDateTime 。但是,是的,您需要编写代码来自己进行调整。正如您所说,您可能需要多种不同的舍入选项,而 Noda Time 很难涵盖所有可能的用例。

我绝对建议编写一个方法来创建一个调整器,而不是仅仅编写一个接受 LocalDateTime 和几分钟的方法——它提供了一种让你非常容易地传递调整器的方法,正如我所展示的,它适合与野田时间自己的调整。 (在 TimeAdjusters DateAdjusters 类中查找我们提供的开箱即用的类。)

如果您需要帮助编写特定的调整器,这可能值得在单独的问题中提出。我不希望它需要双循环等。

关于c# - 使用 NodaTime 舍入时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49386045/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com