如何在两个日期之间创建一个包含30分钟起始/结束时间的日期数组?

huangapple go评论79阅读模式
英文:

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

问题

我有两个日期1/1/2023:12.00.00作为开始和3/3/2023: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
一直到3/3/2023:12.00.00

有人知道在C#中实现这个的简单方法吗?

提前感谢所有人。

英文:

I have two dates 1/1/2023:12.00.00 as the start and 3/3/2023:12.00.00

I want to create a list of dates between these two dates with half an hour start/end time slots, for example
1/1/2023:12.00.00 - 1/1/2023:12.30.00
1/1/2023:12.30.00 - 1/1/2023:13.00.00
all the way up to 3/3/2023:12.00.00

Does any one know a nice and simple way to do this in c#?

All thanks in advance

答案1

得分: 2

你可以将其制作成函数,以将其管理为 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));
英文:

You can make it as functions to manage it as an IEnumerable

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

And use this

var dates = GetDates(new DateTime(2023, 1, 1), new DateTime(2023, 1, 3), TimeSpan.FromMinutes(30));

答案2

得分: 1

以下是您提供的代码的中文翻译:

我有以下的扩展方法适用于此;

/// <summary>
/// 处理 <see cref="DateTime"/> 的扩展方法
/// </summary>
public static class DateTimeExtensions
{

    #region 范围

    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>
    /// 改编自 <see href="https://stackoverflow.com/a/39847791/4122889">的代码
    /// <example>
    /// // 相同的结果
    /// 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
...
英文:

I have the following extension methods lying around for this;

/// &lt;summary&gt;
/// Extensions for dealing with &lt;see cref=&quot;DateTime&quot;/&gt;
/// &lt;/summary&gt;
public static class DateTimeExtensions
{

    #region Range

    private static readonly Func&lt;DateTime, DateTime&gt; DayStep = x =&gt; x.AddDays(1);
    private static readonly Func&lt;DateTime, DateTime&gt; MonthStep = x =&gt; x.AddMonths(1);
    private static readonly Func&lt;DateTime, DateTime&gt; YearStep = x =&gt; x.AddYears(1);

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

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

    public static IEnumerable&lt;DateTime&gt; RangeToMonthly(this DateTime from, DateTime to)
        =&gt; RangeTo(from, to, MonthStep);

    public static IEnumerable&lt;DateTime&gt; RangeToYearly(this DateTime from, DateTime to)
        =&gt; RangeTo(from, to, YearStep);


    public static IEnumerable&lt;DateTime&gt; RangeFrom(this DateTime to, DateTime from, Func&lt;DateTime, DateTime&gt;? step = null) 
        =&gt; from.RangeTo(to, step);

    #endregion
}

Usage;

DateTime.UtcNow.RangeTo(DateTime.UtcNow.AddDays(1), x =&gt; 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
...

答案3

得分: 0

保持调用 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);
}
英文:

Keep calling AddMinutes() to obtain the next value:

var dateTimeValues = new List&lt;DateTime&gt;();

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

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

答案4

得分: 0

Sure, here are the translated code sections:

liq and Enumerable approach:


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();

Another way - cleaner:

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

The result would be an IEnumerable.

英文:

liq and Enumerable approach:


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 =&gt; startDate.Add(TimeSpan.FromMinutes(30 * multiplier)))
		  .TakeWhile(span =&gt; span &lt;= endDate);

dates.Dump();

another way - cleaner:

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

result would be IEnumerable
如何在两个日期之间创建一个包含30分钟起始/结束时间的日期数组?

答案5

得分: 0

你甚至可以使用一个简单的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天。

英文:

You can even use a simple for-loop:

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

You may need to add 1 day to the enddate, if you want to include date ranges on that day.

huangapple
  • 本文由 发表于 2023年6月27日 19:54:39
  • 转载请务必保留本文链接:https://go.coder-hub.com/76564596.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定