PHP函式:DatePeriod::getStartDate()
適用版本:PHP 5 >= 5.6.5, PHP 7
用法:DatePeriod::getStartDate() 方法用於獲取 DatePeriod 物件的起始日期。
語法:public DateTimeInterface|null DatePeriod::getStartDate (void)
引數:此方法不接受任何引數。
返回值:如果 DatePeriod 物件的起始日期已設定,則返回 DateTimeInterface 物件;如果未設定,則返回 null。
示例:
// 建立一個 DatePeriod 物件
$start = new DateTime('2022-01-01');
$end = new DateTime('2022-01-10');
$interval = new DateInterval('P1D');
$period = new DatePeriod($start, $interval, $end);
// 獲取 DatePeriod 物件的起始日期
$startDate = $period->getStartDate();
if ($startDate instanceof DateTimeInterface) {
echo "起始日期: " . $startDate->format('Y-m-d');
} else {
echo "起始日期未設定";
}
輸出:
起始日期: 2022-01-01
在這個示例中,我們首先建立了一個 DatePeriod 物件,該物件表示從 2022-01-01 到 2022-01-10 的日期範圍,間隔為 1 天。然後,我們使用 getStartDate() 方法獲取 DatePeriod 物件的起始日期,並透過判斷返回值是否為 DateTimeInterface 物件來確定起始日期是否已設定。最後,我們使用 format() 方法將起始日期格式化為年-月-日的形式,並將其輸出到螢幕上。