首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> 關於C語言

C# 實作 DateDiff 函式:依間隔單位計算兩日期差異

     編輯:關於C語言

需求背景

VB.NET 內建 DateDiff 函式,C# 無直接對應方法。本文提供一個靜態工具類別,模擬 VB 風格依指定間隔(秒、分、時、日、週、月、季、年)回傳長整數差異值。

完整程式碼

public enum DateInterval
{
    Second, Minute, Hour, Day, Week, Month, Quarter, Year
}

public sealed class DateTimeHelper
{
    private DateTimeHelper() { } // 靜態類別模式

    public static long DateDiff(DateInterval interval, DateTime start, DateTime end)
    {
        TimeSpan ts = new TimeSpan(end.Ticks - start.Ticks);
        return interval switch
        {
            DateInterval.Second  => (long)ts.TotalSeconds,
            DateInterval.Minute  => (long)ts.TotalMinutes,
            DateInterval.Hour    => (long)ts.TotalHours,
            DateInterval.Day     => ts.Days,
            DateInterval.Week    => ts.Days / 7,
            DateInterval.Month   => ts.Days / 30,      // 近似值
            DateInterval.Quarter => ts.Days / 90,      // 近似值
            DateInterval.Year    => ts.Days / 365,     // 近似值
            _ => 0
        };
    }
}

使用範例

DateTime d1 = DateTime.Now;
DateTime d2 = d1.AddYears(2);

Console.WriteLine($"Days     : {DateTimeHelper.DateDiff(DateInterval.Day, d1, d2)}");
Console.WriteLine($"Hours    : {DateTimeHelper.DateDiff(DateInterval.Hour, d1, d2)}");
Console.WriteLine($"Minutes  : {DateTimeHelper.DateDiff(DateInterval.Minute, d1, d2)}");
Console.WriteLine($"Months   : {DateTimeHelper.DateDiff(DateInterval.Month, d1, d2)}");
Console.WriteLine($"Quarters : {DateTimeHelper.DateDiff(DateInterval.Quarter, d1, d2)}");
Console.WriteLine($"Seconds  : {DateTimeHelper.DateDiff(DateInterval.Second, d1, d2)}");
Console.WriteLine($"Weeks    : {DateTimeHelper.DateDiff(DateInterval.Week, d1, d2)}");
Console.WriteLine($"Years    : {DateTimeHelper.DateDiff(DateInterval.Year, d1, d2)}");

注意事項與改進建議

  • 月/季/年為近似值:以固定天數除法計算,無法精確處理月份長短與閏年。精確需求請改用 ((end.Year - start.Year) * 12) + end.Month - start.Month 等邏輯。
  • TimeSpan 已處理負值情況(end < start 時回傳負數),符合直覺。
  • 若需更精確的商業日期計算,建議引入 NodaTime 或自行實作月份差異演算法。

現代 C# 簡寫版

public static long DateDiff(DateInterval interval, DateTime start, DateTime end)
    => interval switch
    {
        DateInterval.Second  => (long)(end - start).TotalSeconds,
        DateInterval.Minute  => (long)(end - start).TotalMinutes,
        DateInterval.Hour    => (long)(end - start).TotalHours,
        DateInterval.Day     => (end - start).Days,
        DateInterval.Week    => (end - start).Days / 7,
        DateInterval.Month   => (end.Year - start.Year) * 12 + end.Month - start.Month,
        DateInterval.Quarter => ((end.Year - start.Year) * 12 + end.Month - start.Month) / 3,
        DateInterval.Year    => end.Year - start.Year,
        _ => 0
    };

此版本月/季/年計算更符合商業邏輯,建議專案實際採用。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved