C# (.NET) 中的日期处理:库与内置工具概览

面向初学者的在线Python训练器

轻松学习Python,无需理论负担。在浏览器中直接解决带自动检查的实践任务,无需安装任何东西。

开始课程

在 C# (.NET) 中处理日期:从内置工具到专业库



日期和时间的处理是任何应用程序开发中的关键任务之一:从 Web 服务到桌面工具。.NET 平台提供了强大的内置工具,例如 DateTime、DateTimeOffset 和 TimeSpan。然而,在复杂场景下(处理时区、人类可读的时间间隔、解析非标准格式),开发人员通常会求助于第三方库。在本文中,我们将介绍 C# 中用于处理日期的主要工具。



1. .NET 内置工具



.NET 中用于处理日期的基础类型:



  • DateTime — 表示一个时间点(日期 + 时间)。支持加法、减法、比较操作。
  • DateTimeOffset — 类似于 DateTime,但显式指定了相对于 UTC 的偏移量。建议用于在分布式系统中存储日期。
  • TimeSpan — 时间间隔(例如,2 小时 30 分钟)。
  • DateOnly 和 TimeOnly(自 .NET 6 起)— 用于分别存储日期和时间,不包含多余数据。


DateTime 使用示例:

using System;

DateTime now = DateTime.Now;DateTime utcNow = DateTime.UtcNow;DateTime specificDate = new DateTime(2025, 3, 15, 14, 30, 0);

// 格式化string formatted = now.ToString("dd.MM.yyyy HH:mm:ss");Console.WriteLine(formatted); // 15.03.2025 14:30:00

// 算术运算DateTime tomorrow = now.AddDays(1);TimeSpan diff = tomorrow - now;Console.WriteLine($"距离明天:{diff.TotalHours} 小时");


从字符串解析日期:

string dateStr = "2025-03-15";if (DateTime.TryParse(dateStr, out DateTime result)){    Console.WriteLine(result.ToShortDateString());}

// 指定区域性的解析var culture = new System.Globalization.CultureInfo("ru-RU");DateTime parsed = DateTime.Parse("15 марта 2025", culture);


2. Noda Time — 高级日期和时间处理



Noda Time — 一个社区开发的替代库,旨在弥补内置 DateTime 的不足。主要特点:



  • 概念清晰分离:Instant(UTC 时刻)、LocalDateTime(不绑定时区的日期+时间)、ZonedDateTime(带时区)。
  • 通过 IANA (Olson) 数据库完全支持时区。
  • 不可变 (immutable) 类型 — 在多线程代码中安全。
  • 人类可读的时间间隔 (Period):2 年、3 个月、5 天。


Noda Time 使用示例:

using NodaTime;using NodaTime.Text;

// UTC 当前时刻Instant now = SystemClock.Instance.GetCurrentInstant();Console.WriteLine($"Instant: {now}");

// 转换为带时区的本地时间DateTimeZone zone = DateTimeZoneProviders.Tzdb["Europe/Moscow"];ZonedDateTime moscowTime = now.InZone(zone);Console.WriteLine($"莫斯科时间:{moscowTime}");

// 以特定格式解析日期var pattern = LocalDatePattern.CreateWithInvariantCulture("yyyy-MM-dd");LocalDate date = pattern.Parse("2025-03-15").Value;Console.WriteLine(date); // 2025年3月15日

// 处理时间段LocalDate start = new LocalDate(2025, 1, 1);LocalDate end = new LocalDate(2025, 12, 31);Period period = Period.Between(start, end, PeriodUnits.Days);Console.WriteLine($"日期之间的天数:{period.Days}");


3. Humanizer — 人类可读的日期和时间间隔



Humanizer — 一个用于将数字、日期和字符串转换为人类友好格式的库。在日期方面,它

推荐