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 ::