略微加速

PHP官方手册 - 互联网笔记

PHP - Manual: DateTime::setDate

2024-11-14

DateTime::setDate

date_date_set

(PHP 5 >= 5.2.0, PHP 7, PHP 8)

DateTime::setDate -- date_date_set设置 DateTime 对象的日期

说明

面向对象风格

public DateTime::setDate(int $year, int $month, int $day): DateTime

过程化风格

date_date_set(
    DateTime $object,
    int $year,
    int $month,
    int $day
): DateTime

设置 DateTime 对象的日期。

参数

object

仅过程化风格:由 date_create() 返回的 DateTime 类型的对象。此函数会修改这个对象。

year

年份。

month

月份。

day

日。

返回值

返回被修改的 DateTime 对象, 或者在失败时返回 false.

范例

示例 #1 DateTime::setDate() 例程

面向对象风格

<?php
$date 
= new DateTime();
$date->setDate(200123);
echo 
$date->format('Y-m-d');
?>

过程化风格

<?php
$date 
date_create();
date_date_set($date200123);
echo 
date_format($date'Y-m-d');
?>

以上例程会输出:

2001-02-03

示例 #2 超出范围的部分会向上一级增加

<?php
$date 
= new DateTime();

$date->setDate(2001228);
echo 
$date->format('Y-m-d') . "\n";

$date->setDate(2001229);
echo 
$date->format('Y-m-d') . "\n";

$date->setDate(2001143);
echo 
$date->format('Y-m-d') . "\n";
?>

以上例程会输出:

2001-02-28
2001-03-01
2002-02-03

参见

add a noteadd a note

User Contributed Notes 3 notes

up
7
kevin dot nadin at gmail dot com
5 years ago
Be carreful about this bug in php 5.6 and lower (fixed in php 7.0 and higher) :

<?php
$date
= new DateTime("first day of last month");
echo
$date->format('Y-m-d');
echo 
' => ' ;
$date->setDate(2013, 2, 3);
echo
$date->format('Y-m-d');
?>

Output <=5.6 : 2017-03-01 => 2013-02-01
Output >=7.0 : 2017-03-31 => 2013-02-03

Same goes for "Last day of last month", and the funny part, it will take the last day of the new month setted by setDate

Example with a Leap Year :
<?php
$date
= new DateTime("last day of last month");
echo
$date->format('Y-m-d');
echo 
' => ' ;
$date->setDate(2012, 2, 3);
echo
$date->format('Y-m-d');
?>

Output <=5.6 : 2017-03-31 => 2012-02-29
Output >=7.0 : 2017-03-31 => 2012-02-03
up
3
remy215 at laposte dot net
10 years ago
Be warned, DateTime::setDate() does not check for invalid input.

Illustration:
<?php
$dt
= new DateTime();
$dt->setDate(2012, 11, 31); // returns DateTime object and not false although this date does not exist
echo $dt->format('Y-m-d'); // output: 2012-12-01
?>

No error was generated on entering a non existing date, php silently changed it.
up
-4
kevin dot nadin at gmail dot com
5 years ago
Correction on the previous comment :

Bug fixed in php 7.0.17 and 7.1.3, for the version 7.0.0 to 7.0.16 and 7.1.0 to 7.1.2, the bug is still present

官方地址:https://www.php.net/manual/en/datetime.setdate.php

北京半月雨文化科技有限公司.版权所有 京ICP备12026184号-3