C#基础:DateOnly

作者:微信公众号:【架构师老卢】
8-3 18:16
33

概述:在 C# 9.0 及更高版本中,DateOnly 结构在 System 命名空间中可用。DateOnly 旨在表示不带时间部分的日期,从而在不需要考虑时间信息的情况下提供一种更有效、更准确的日期处理方式。这是对使用 DateTime 结构的改进,该结构始终包含时间信息C# 语言中的 DateOnlyC# 中 dateonlt 的功能:创建 DateOnly:您可以创建一个 DateOnly 实例来表示特定日期。它需要年、月和日作为参数:例using System; DateOnly date = new DateOnly(2023, 10, 31);访问日期组件:您可以访问 DateOnly

在 C# 9.0 及更高版本中,DateOnly 结构在 System 命名空间中可用。DateOnly 旨在表示不带时间部分的日期,从而在不需要考虑时间信息的情况下提供一种更有效、更准确的日期处理方式。这是对使用 DateTime 结构的改进,该结构始终包含时间信息

C# 语言中的 DateOnly

C# 中 dateonlt 的功能:

创建 DateOnly:

您可以创建一个 DateOnly 实例来表示特定日期。它需要年、月和日作为参数:

using System;  
DateOnly date = new DateOnly(2023, 10, 31);

访问日期组件:

您可以访问 DateOnly 对象的各种组件,例如年、月和日:

int year = date.Year; // 2023  
int month = date.Month; // 10  
int day = date.Day; // 31

字符串格式:

可以使用 ToString 方法或自定义格式将 DateOnly 实例转换为字符串:

string defaultFormatted = date.ToString(); // "2023-10-31"  
string customFormatted = date.ToString("MM/dd/yyyy"); // "10/31/2023"

算术运算:

您可以对 DateOnly 对象执行算术运算,例如加法和减法:

DateOnly tomorrow = date.AddDays(1); // Add one day;  
DateOnly yesterday = date.AddDays(\-1); // Subtract one day

比较:

您可以使用比较运算符(例如,<,>、<=、>=)来比较 DateOnly 对象,以检查哪个更大或更小:

bool isGreaterThan = tomorrow > yesterday; // Compare two DateOnly instances

C# 中的 DateOnly 示例

using System;  
public class Program  
{  
  public static void Main(string[] args)  
  {  
    DateOnly date = new DateOnly(2023, 10, 31);  
    int year = date.Year; // 2023  
    int month = date.Month; // 10  
    int day = date.Day; // 31  
    Console.WriteLine("Year is = {0}", year);  
    Console.WriteLine("Month is = {0}", month);  
    Console.WriteLine("Day is = {0}", day);  
    string defaultFormatted = date.ToString(); // "2023-10-31"  
    string customFormatted = date.ToString("MM/dd/yyyy"); // "10/31/2023"  
    Console.WriteLine("The default formated date is = {0}", defaultFormatted);  
    Console.WriteLine("The custom formated date is = {0}", customFormatted);  
    DateOnly tomorrow = date.AddDays(1); // Add one day;  
    DateOnly yesterday = date.AddDays(-1); // Subtract one day  
    bool isGreaterThan = tomorrow > yesterday; // Compare two DateOnly instances  
    Console.WriteLine("The tomorrow date is = {0}", tomorrow);  
    Console.WriteLine("The yesterday date is = {0}", yesterday);  
    Console.WriteLine("Is tomorrow greater yesterday = {0}", isGreaterThan);  
  }  
}

输出

Year is = 2023  
Month is = 10  
Day is = 31  
The default formated date is = 31/10/2023  
The custom formated date is = 10/31/2023  
The tomorrow date is = 01/11/2023  
The yesterday date is = 30/10/2023  
Is tomorrow greater yesterday = True

当您需要在时间信息不相关的情况下处理日期值时,DateOnly 非常有用。它提供了更高效、更准确的日期表示,而没有时间分量的开销。对于使用日历、计划或仅对日期部分重要的任何域的应用程序来说,这尤其有价值。

阅读排行