HOWTO · Csharp

C# 中的 DateTime 中设置 null 值

在本文中,你将了解 DateTime 对象的基础知识以及如何在 C# 中使用它来分配空值。

本页内容

在本课中,我们将看到如何为 DateTime 设置 null 值。要完全理解这个概念,我们需要熟悉 DateTime 和可空值的基础知识。

了解 C# 中 DateTime 的基础知识

假设用户想要从 2015 年 12 月 25 日的一天开始开始计时。我们将为 DateTime 对象分配值。

代码片段:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace nulldatetime {
  class Program {
    static void Main(string[] args) {
      DateTime date1 = new DateTime(2015, 12, 25);  // Assgining User Defined Time ;
      Console.WriteLine("Time " + date1);
      Console.ReadKey();
    }
  }
}

输出:

Time 12/25/2015 12:00:00 AM

在 C# 中为 DateTime 分配最大值和最小值

为 DateTime 分配一个最小值将从开始 Min Time: 1/1/0001 12:00:00 AM 开始。Max time 也是如此,它将以时间最大值 Max Time: 12/31/9999 11:59:59 PM 开始时间。

代码片段:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace nulldatetime {
  class Program {
    static void Main(string[] args) {
      // How to Define an uninitialized date. ?
      // First Method to use MinValue field of datetime object
      DateTime date2 = DateTime.MinValue;  // minimum date value
      Console.WriteLine("Time: " + date2);
      // OR
      date2 = DateTime.MaxValue;
      Console.WriteLine("Max Time: " + date2);
      Console.ReadKey();
    }
  }
}

输出:

Min Time: 1/1/0001 12:00:00 AM
Max Time: 12/31/9999 11:59:59 PM

在 C# 中将 null 值分配给 DateTime

DateTime 不可为空,因为默认情况下,它是值类型。值类型是存储在其内存分配中的一种数据形式。

另一方面,如果我们要使用 Nullable DateTime。我们可以为它分配一个 null 值。

代码片段:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace nulldatetime {
  class Program {
    static void Main(string[] args) {
      // By default DateTime is not nullable because it is a Value Type;
      // Problem # Assgin Null value to datetime instead of MAX OR MIN Value.
      //  Using Nullable Type
      Nullable<DateTime> nulldatetime;  // variable declaration
      nulldatetime = DateTime.Now;      // Assgining DateTime to Nullable Object.
      Console.WriteLine("Current Date Is " + nulldatetime);  // printing Date..
      nulldatetime = null;                                   // assgining null to datetime object.
      Console.WriteLine("My Value is  null ::" + nulldatetime);
      Console.ReadKey();
    }
  }
}

输出:

Current Date Is 02/11/2022 18:57:33
My Value is  null ::