DateAndTime.DateSerial(Int32, Int32, Int32) 方法

定義

Date傳回值,代表指定的年份、月和日,並將時間資訊設定為午夜 (00:00:00) 。

public:
 static DateTime DateSerial(int Year, int Month, int Day);
public static DateTime DateSerial (int Year, int Month, int Day);
static member DateSerial : int * int * int -> DateTime
Public Function DateSerial (Year As Integer, Month As Integer, Day As Integer) As DateTime

參數

Year
Int32

必要。 從 1 到 9999 的整數運算式。 不過,也接受這個範圍以下的值。 如果 Year 為 0 到 99,則會解譯為介於 1930 到 2029 之間,如一節所述。 如果 Year 小於 1,則會從目前的年份中減去它。

Month
Int32

必要。 從 1 到 12 的整數運算式。 不過,也接受超過這個範圍的值。 Month 的值會位移 1,且會套用到計算所得年份的一月。 換句話說,(Month - 1) 會加入到一月。 必要時,會重新計算年份。 下列結果將說明這樣的作用:

如果 Month 為 1,則結果為計算所得年份的一月。

如果 Month 為 0,則結果為前一年度的十二月。

如果 Month 為 -1,則結果為前一年度的十一月。

如果 Month 為 13,則結果為下一年度的一月。

Day
Int32

必要。 從 1 到 31 的整數運算式。 不過,也接受超過這個範圍的值。 Day 的值會位移 1,且會套用到計算所得月份的第一天。 換句話說,(Day - 1) 會加入到此月份的第一天。 必要時,會重新計算月份和年份。 下列結果將說明這樣的作用:

如果 Day 為 1,則結果為計算所得月份的第一天。

如果 Day 為 0,則結果為上一月份的最後一天。

如果 Day 為 -1,則結果為上一月份的倒數第二天。

如果 Day 超過目前月份的結尾,則結果為下一月份的適當日。 例如,如果 Month 是 4 且 Day 為 31,結果會是 5 月 1 日。

傳回

值,表示指定的年份、月和日,並將時間資訊設定為午夜 (00:00:00) 。

範例

本範例會使用 函 DateSerial 式傳回指定年份、月份和日期的日期。

' DateSerial returns the date for a specified year, month, and day.
Dim aDate As Date
' Variable aDate contains the date for February 12, 1969.
aDate = DateSerial(1969, 2, 12)
Console.WriteLine(aDate)

' The following example uses DateSerial to determine and display
' the last day of the previous month.
' First, establish a starting date.
Dim startDate = #1/23/1994#
' The 0 for the day represents the last day of the previous month.
Dim endOfLastMonth = DateSerial(startDate.Year, startDate.Month, 0)
Console.WriteLine("Last day in the previous month: " & endOfLastMonth)

' The following example finds and displays the day of the week that the 
' 15th day of the following month will fall on.
Dim fifteenthsDay = DateSerial(Today.Year, Today.Month + 1, 15)
Console.WriteLine("The 15th of next month is a {0}", fifteenthsDay.DayOfWeek)

備註

自變數的 Year 兩位數值會根據使用者定義的電腦設定來解譯。 默認設定是 0 到 29 的值會解譯為 2000-2029 年,而 30 到 99 的值會解譯為 1930-1999 年。 若要表示所有其他年份,請使用四位數年份,例如 1924。

下列範例示範負數、零和正自變數值。 在這裡,函 DateSerial 式會傳回 , Date 代表當年 10 年前 3 月第一天之前的日期;換句話說,2 月 10 日前的最後一天。

Dim EndFeb As Date = DateSerial(-10, 3, 0)  

Month如果或Day超過其一般範圍,則會視需要套用至下一個較大的單位。 例如,如果您指定 32 天,則會根據 的值 Month評估為一個月,並從一到四天評估。 如果 Year 大於 9999,或任何自變數超出範圍 -2,147,483,648 到 2,147,483,647,則 ArgumentException 會發生錯誤。 如果三個自變數指定的日期早於 1 年 1 月 1 日 00:00:00,或晚於 23:59:59 於 9999 年 12 月 31 日之後, ArgumentOutOfRangeException 就會發生錯誤。

Date數據類型包含時間元件。 DateSerial 會將所有這些設定為 0,因此傳回的值代表計算日期的開頭。

由於結構支援DateTime每個Date值,因此其方法會提供您組合Date值的其他選項。 例如,您可以使用其中一個多載 DateTime 建構函式,使用所需的元件組合來填入 Date 變數。 下列範例會將 1978 年 5 月 6 日設定 NewDateTime 為上午 8:30 之前的一分之一秒:

Dim NewDateTime As Date = New Date(1978, 5, 6, 8, 29, 59, 900)  

適用於

另請參閱