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

C# 比較字串格式日期大小:DateTime.Parse 直接比較

     編輯:關於C#

最簡單做法

string beginTime = "2024/03/15 14:30:00";
string endTime   = "2024/03/15 16:00:00";

if (DateTime.Parse(beginTime) > DateTime.Parse(endTime))
{
    Console.WriteLine("開始時間晚於結束時間,邏輯錯誤");
}

進階:指定格式與文化特性 (效能更好、避免歧義)

string fmt = "yyyy/MM/dd HH:mm:ss";
var culture = CultureInfo.InvariantCulture;

DateTime start = DateTime.ParseExact(beginTime, fmt, culture);
DateTime end   = DateTime.ParseExact(endTime, fmt, culture);

if (start > end) { /* ... */ }

安全解析:TryParse 避免例外

if (DateTime.TryParse(beginTime, out DateTime start) &&
    DateTime.TryParse(endTime, out DateTime end))
{
    if (start > end) { /* ... */ }
}
else
{
    Console.WriteLine("日期格式錯誤");
}

比較結果應用

public int CompareDateStrings(string date1, string date2, string format = null)
{
    DateTime d1, d2;
    bool ok = format == null
        ? DateTime.TryParse(date1, out d1) && DateTime.TryParse(date2, out d2)
        : DateTime.TryParseExact(date1, format, CultureInfo.InvariantCulture, DateTimeStyles.None, out d1) &&
          DateTime.TryParseExact(date2, format, CultureInfo.InvariantCulture, DateTimeStyles.None, out d2);

    if (!ok) throw new ArgumentException("日期格式無法解析");

    return d1.CompareTo(d2); // -1: d1d2
}

注意事項

  • 字串直接比較 (`string.Compare`) **不可用** 於日期,除非格式為固定寬度、降冪排序 (如 `yyyy-MM-dd HH:mm:ss`),否則 `03/15` > `12/01` (字串比較) 但實際日期較早。
  • `DateTime.Parse` 使用目前執行緒文化特性,跨地區部署易出錯,建議明確指定 `CultureInfo.InvariantCulture` 或 `ParseExact`。
  • 大量比較 (如排序) 時,先轉換為 `DateTime` 陣列再排序,避免重複解析。

參考資源

原文連結:https://www.bianceng.cn/Programming/csharp/201410/45575.htm

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