You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在C#中生成两个日期间间隔30分钟的时间槽数组?

简洁的C#实现方法

可以通过日期时间解析 + 循环/ LINQ 生成的方式快速实现需求,逻辑清晰且代码简洁,具体实现如下:

1. 核心思路

  • 先将用户提供的字符串格式日期转换为DateTime类型,需指定匹配的格式字符串确保解析准确
  • 从起始时间开始,每次递增30分钟生成时间槽,直到槽的结束时间不超过目标结束日期
  • 将每个时间槽的起止时间格式化为需求的字符串样式

完整代码示例(循环版)

using System;
using System.Collections.Generic;

class TimeSlotGenerator
{
    static void Main()
    {
        // 定义起始和结束时间字符串
        string startDateStr = "1/1/2023:12.00.00";
        string endDateStr = "3/3/2023:12.00.00";
        
        // 解析日期(兼容单/双位的日、月)
        DateTime startTime = DateTime.ParseExact(startDateStr, "d/M/yyyy:H.m.s", null);
        DateTime endTime = DateTime.ParseExact(endDateStr, "d/M/yyyy:H.m.s", null);
        
        // 存储时间槽的列表
        List<string> timeSlots = new List<string>();
        
        DateTime currentTime = startTime;
        while (currentTime < endTime)
        {
            DateTime nextTime = currentTime.AddMinutes(30);
            // 格式化为需求的字符串样式
            string slot = $"{currentTime.ToString("d/M/yyyy:H.m.s")} - {nextTime.ToString("d/M/yyyy:H.m.s")}";
            timeSlots.Add(slot);
            
            currentTime = nextTime;
        }
        
        // 输出示例(可根据需求自行处理列表)
        foreach (var slot in timeSlots)
        {
            Console.WriteLine(slot);
        }
    }
}

更紧凑的LINQ版实现

如果偏好更简洁的写法,可通过LINQ直接生成所有时间槽:

using System;
using System.Collections.Generic;
using System.Linq;

class TimeSlotGenerator
{
    static void Main()
    {
        string startDateStr = "1/1/2023:12.00.00";
        string endDateStr = "3/3/2023:12.00.00";
        DateTime startTime = DateTime.ParseExact(startDateStr, "d/M/yyyy:H.m.s", null);
        DateTime endTime = DateTime.ParseExact(endDateStr, "d/M/yyyy:H.m.s", null);
        
        // 计算总时间槽数量
        int totalSlots = (int)((endTime - startTime).TotalMinutes / 30);
        // 生成所有时间槽
        List<string> timeSlots = Enumerable.Range(0, totalSlots)
            .Select(i => 
            {
                DateTime slotStart = startTime.AddMinutes(i * 30);
                DateTime slotEnd = slotStart.AddMinutes(30);
                return $"{slotStart.ToString("d/M/yyyy:H.m.s")} - {slotEnd.ToString("d/M/yyyy:H.m.s")}";
            })
            .ToList();
        
        // 输出处理
        foreach (var slot in timeSlots)
        {
            Console.WriteLine(slot);
        }
    }
}

代码说明

  • 使用DateTime.ParseExact而非默认Parse,避免因系统区域设置差异导致解析错误
  • 两种实现均会生成包含结束时间点的最后一个时间槽(即3/3/2023:11.30.00 - 3/3/2023:12.00.00)
  • 格式字符串d/M/yyyy:H.m.s兼容单/双位的日、月、时、分、秒,适配用户提供的日期格式

内容的提问来源于stack exchange,提问作者Calibre2010

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.17 22:52:49