如何在 2 个日期之间创建具有 30 分钟开始/结束时间的日期数组?

how do i create an array of dates with 30 minute start / end times between 2 dates?

提问人:Calibre2010 提问时间:6/27/2023 最后编辑:Rand RandomCalibre2010 更新时间:6/27/2023 访问量:75

问:

我有两个日期,2023 年 1 月 1 日:12.00.00 作为开始,以及 2023 年 3 月 3 日:12.00.00

例如,我想在这两个日期之间创建一个日期列表,其中包含半小时的开始/结束时间段 1/1/2023:12.00.00 - 1/1/2023:12.30.00 1/1/2023:12.30.00 - 1/1/2023:13.00.00 一直到 2023/3/3:12.00.00

有没有人知道在 c# 中做到这一点的好方法?

提前致谢

C# .NET 日期时间

评论

1赞 sommmen 6/27/2023
这回答了你的问题吗?如何循环浏览日期范围?

答:

0赞 Mathias R. Jessen 6/27/2023 #1

继续调用 AddMinutes() 以获取下一个值:

var dateTimeValues = new List<DateTime>();

var startDate = new DateTime(2023, 1, 1);
var endDate = new DateTime(2023, 1, 3);

var currentDateTime = startDate;
while ((currentDateTime = currentDateTime.AddMinutes(30)) <= endDate) {
    dateTimeValues.Add(currentDateTime);
}

评论

0赞 Rand Random 6/27/2023
吹毛求疵:“如何创建数组...”(没关系......在问题正文中,OP 提到列表而不是数组)
0赞 Power Mouse 6/27/2023 #2

liq 和 Enumerable 方法:


var startDate = new DateTime(2023,1,1, 12,00,00);
var endDate = new DateTime(2023,3,3, 12,00,00);

var dates = Enumerable.Range(0, int.MaxValue)
          .Select(multiplier => startDate.Add(TimeSpan.FromMinutes(30 * multiplier)))
          .TakeWhile(span => span <= endDate);

dates.Dump();

另一种方式 - 清洁剂:

int chunks = (int)(endDate - startDate).TotalMinutes / 30;
    var rez =  Enumerable.Range(0, chunks + 1)
                     .Select(p => startDate.AddMinutes(30 * p));
                     

result 将是 IEnumerableenter image description here

2赞 Daniel127 6/27/2023 #3

您可以将其作为函数来将其作为 IEnumerable 进行管理

public IEnumerable<DateTime> GetDates(DateTime startDate, DateTime endDate, TimeSpan interval)
{
    var currentDateTime = startDate;
    while (currentDateTime < endDate)
    {
        yield return currentDateTime;
        currentDateTime = currentDateTime.Add(interval);
    }
    yield return endDate;
}

并使用它

var dates = GetDates(new DateTime(2023, 1, 1), new DateTime(2023, 1, 3), TimeSpan.FromMinutes(30));
1赞 sommmen 6/27/2023 #4

为此,我有以下扩展方法;

/// <summary>
/// Extensions for dealing with <see cref="DateTime"/>
/// </summary>
public static class DateTimeExtensions
{

    #region Range

    private static readonly Func<DateTime, DateTime> DayStep = x => x.AddDays(1);
    private static readonly Func<DateTime, DateTime> MonthStep = x => x.AddMonths(1);
    private static readonly Func<DateTime, DateTime> YearStep = x => x.AddYears(1);

    /// <summary>
    /// Adapted from <see href="https://stackoverflow.com/a/39847791/4122889"/>
    /// <example>
    /// // same result
    /// var fromToday = birthday.RangeFrom(today);
    /// var toBirthday = today.RangeTo(birthday);
    /// </example>
    /// </summary>
    /// <param name="from"></param>
    /// <param name="to"></param>
    /// <param name="step"></param>
    /// <returns></returns>
    public static IEnumerable<DateTime> RangeTo(this DateTime from, DateTime to, Func<DateTime, DateTime>? step = null)
    {
        step ??= DayStep;

        while (from < to)
        {
            yield return from;
            from = step(from);
        }
    }

    public static IEnumerable<DateTime> RangeToMonthly(this DateTime from, DateTime to)
        => RangeTo(from, to, MonthStep);

    public static IEnumerable<DateTime> RangeToYearly(this DateTime from, DateTime to)
        => RangeTo(from, to, YearStep);


    public static IEnumerable<DateTime> RangeFrom(this DateTime to, DateTime from, Func<DateTime, DateTime>? step = null) 
        => from.RangeTo(to, step);

    #endregion
}

用法;

DateTime.UtcNow.RangeTo(DateTime.UtcNow.AddDays(1), x => x.AddMinutes(30)).ToList()
06/27/2023 12:31:36
06/27/2023 13:01:36
06/27/2023 13:31:36
06/27/2023 14:01:36
06/27/2023 14:31:36
...

评论

0赞 Rand Random 6/27/2023
恕我直言,函数的开销似乎是不必要的,只需传递一个时间跨度或一个 int。
0赞 Hans Kesting 6/27/2023 #5

您甚至可以使用简单的 -loop:for

TimeSpan interval = TimeSpan.FromMinutes(30);
for (var dt=new DateTime(2023,1,1); dt<new DateTime(2023,3,3); dt = dt.Add(interval))
{
    Console.WriteLine($"{dt:yyyy-MM-dd HH:mm} - {dt.Add(interval):yyyy-MM-dd HH:mm}");
}

如果要包含当天的日期范围,则可能需要在结束日期上添加 1 天。