PHP 5.6.0beta1 released

DateTime::setDate

date_date_set

(PHP 5 >= 5.2.0)

DateTime::setDate -- date_date_setSets the date

说明

面向对象风格

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

过程化风格

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

Resets the current date of the DateTime object to a different date.

参数

object

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

year

Year of the date.

month

Month of the date.

day

Day of the date.

返回值

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

更新日志

版本 说明
5.3.0将返回值从NULL改为 DateTime 类型。

范例

Example #1 DateTime::setDate() example

面向对象风格

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

Example #2 Values exceeding ranges are added to their parent values

<?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 note add a note

User Contributed Notes 1 note

up
5
remy215 at laposte dot net
2 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.
To Top