---
# System prepended metadata

title: 'C# 時間區間清單Function'
tags: ['C#']

---

### C# 算出時間區間(以日計算)
```
  /// <summary>
    /// 時間區間比對
    /// </summary>
    /// <param name="fromDate"></param>
    /// <param name="toDate"></param>
    /// <returns></returns>
    private IEnumerable<DateTime> DateRange(DateTime fromDate, DateTime toDate)
    {
        return Enumerable.Range(0, toDate.Subtract(fromDate).Days + 1)
            .Select(d => fromDate.AddDays(d));
    }
```

### 給定日期，列出當天從0000~2359所有10分鐘的時間清單

```
/// <summary>
        /// 取得一天全部的10分鐘區間
        /// </summary>
        /// <param name="fromDate"></param>
        /// <param name="toDate"></param>
        /// <returns></returns>
        public Dictionary<DateTime, DateTime> AllTenMinute(DateTime dt)
        {
            var result = new Dictionary<DateTime, DateTime>();
            dt = dt.Date;
            for (DateTime _dt = dt; _dt < new DateTime(dt.Year,dt.Month,dt.Day,23,59,59); _dt = _dt.AddMinutes(10))
            {
                result.Add(_dt, _dt.AddMinutes(10));
            }
            
            return result;
        }
```

#### 給定日期，列出當天從0000~2359每小時的時間清單

   ```
/// <summary>
    /// 小時區間
    /// </summary>
    /// <returns>前一個區間起,前一個區間結</returns>
    public KeyValuePair<DateTime, DateTime> HourInterval(DateTime dt)
    {
        //從當日00:00開始算，無視現在時間
        DateTime dtZeroTime = dt.Date;
        var result = new Dictionary<DateTime, DateTime>();
        for (var day = dtZeroTime.Date; day <= dt; day = day.AddHours(1))
        {
            result.Add(day.AddMinutes(-59), day.AddMinutes(-1));
        }
        //取出最後一個時間，即為小時區間
        return new KeyValuePair<DateTime, DateTime>(result.Last().Key, result.Last().Value);
    }
```


#### 給定日期，列出該日期的當周所有日期(星期日~六)

```
/// <summary>
/// 周區間算法
/// </summary>
/// <param name="fromDate"></param>
/// <param name="toDate"></param>
/// <returns></returns>
public Dictionary<DateTime, DateTime> WeekRange(DateTime dateData)
{
    var result = new Dictionary<DateTime, DateTime>();

    for (int i = 7; i >= 1; i--)
    {
        var dayS = new DateTime(dateData.Year, dateData.Month, dateData.Day, 00, 00, 00);
        var dayE = new DateTime(dateData.Year, dateData.Month, dateData.Day, 23, 59, 59);
        result.Add(dayS, dayE);
        dateData = dateData.AddDays(-1);
    }

    return result;
    }
```