略微加速

PHP官方手册 - 互联网笔记

PHP - Manual: date_create

2024-11-14

date_create

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

date_createcreate a new DateTime object

说明

date_create(string $datetime = "now", ?DateTimeZone $timezone = null): DateTime|false

This is the procedural version of DateTime::__construct().

Unlike the DateTime constructor, it will return false instead of an exception if the passed in datetime string is invalid.

返回值

Returns a new DateTime instance. 过程化风格在失败时返回 false

参见

add a noteadd a note

User Contributed Notes 10 notes

up
29
Dok
14 years ago
If you want to create the DateTime object directly from a timestamp use this

<?php
$st
= 1170288000 //  a timestamp
$dt = new DateTime("@$st");
?>

See also: http://bugs.php.net/bug.php?id=40171
up
18
Marton Bodonyi
9 years ago
If you are getting an error like this:

Exception: DateTime::__construct(): Failed to parse time string (13/02/2013) at position 0 (1): Unexpected character in DateTime->__construct()

Note that when you create a new date object using a format with slashes and dashes (eg 02-02-2012 or 02/02/2012) it must be in the mm/dd/yy(yy) or mm-dd-yy(yy) format (rather than british format dd/mm/yy)! Months always before years (the american style) otherwise you'll get an incorrect date and may get an error like the one above (where PHP is crashing on trying to decode a 13th month).

Can catch you off guard because everything seems to be working fine and dandy until you hit a value over 12.
up
1
A. Go
3 years ago
Notice php by default assume the give string as such format:
'-'    is    'y-m-d'
'/'    is    'm/d/y'

Unless the given string has Y or M,
that is year is written as full year '2019', or month is written as English shorthand 'Jan',
the default assumption will be applied, where the date might be incorrect.

The following code show a quick test: (true as of php 7.2)
$date = [
    '2019-1-3',
    '19-1-3',
    '3-1-2019',
    '3-Jan-19',
    '3-1-19', //php assume as y-m-d not d-m-y

    '2019-3-1',
    '19-3-1',
    '1-3-2019',
    '1-3-19',

    '2019/3/1',
    '19/3/1', //fail, php think is month 19
    '1/3/2019', //php think is m/d/y
    '1/3/19'
];

//Y-M-d
foreach($date as $i => $d){
    echo $i ."\r\n";
    var_dump(date_format(date_create($d), 'Y-M-d'));
    echo "\r\n";
}
up
6
artur at jedlinski dot pl
15 years ago
"String in a format accepted by strtotime()" is not 100% truth - you cannot pass timezone info in the string used as DateTime constructor, while you can do it with strtotime(). It may be a problem if you would like to create a date from GMT time and then display it in your local timezone, for example:

<?php
    $timeZone
= 'Europe/Warsaw'// +2 hours
   
date_default_timezone_set($timeZone);
   
   
$dateSrc = '2007-04-19 12:50 GMT';
   
$dateTime = new DateTime($dateSrc);
   
    echo
'date(): '.date('H:i:s', strtotime($dateSrc));
   
// correct! date(): 14:50:00
   
   
echo 'DateTime::format(): '.$dateTime->format('H:i:s');
   
// INCORRECT! DateTime::format(): 12:50:00
?>

[red. your claim that "is not 100% truth" is incorrect, you're seeing desired behavior here. The timezone passed as 2nd argument is used as a default fall back, in case the parsed string doesn't provide TZ information.]

So if you want to convert date between different timezones, you have to create two DateTimeZone objects - one for the input and one for output, like this:

<?php
    $timeZone
= 'Europe/Warsaw'// +2 hours
   
$dateSrc = '2007-04-19 12:50';
   
   
$dateTime = new DateTime($dateSrc, new DateTimeZone('GMT'));
   
$dateTime->setTimeZone(new DateTimeZone($timeZone));
    echo
'DateTime::format(): '.$dateTime->format('H:i:s');
   
// CORRECT! DateTime::format(): 14:50:00
?>

I'm not sure if this is a bug or desired behaviour.
[red. you don't have to do create two DateTimeZone objects, this works too:
<?php
    $timeZone
= 'Europe/Warsaw'// +2 hours
   
$dateSrc = '2007-04-19 12:50 GMT';
   
   
$dateTime = new DateTime($dateSrc);
   
$dateTime->setTimeZone(new DateTimeZone($timeZone));
    echo
'DateTime::format(): '.$dateTime->format('H:i:s');
   
// CORRECT! DateTime::format(): 14:50:00
?>
]
up
1
Eugene
7 years ago
@Marton Bodonyi
This is not exactly true.

The following code:
[code]
echo "1\n";
print_r(date_create('13-02-2013'));
echo "2\n";
print_r(date_create('13/02/2013'));
echo "3\n";
print_r(new DateTime('13-02-2013'));
echo "4\n";
print_r(new DateTime('13/02/2013'));
[/code]

produces the following output:
[code]
1
DateTime Object
(
    [date] => 2013-02-13 00:00:00.000000
    [timezone_type] => 3
    [timezone] => Europe/London
)
2
3
DateTime Object
(
    [date] => 2013-02-13 00:00:00.000000
    [timezone_type] => 3
    [timezone] => Europe/London
)
4
<br />
<b>Fatal error</b>:  Uncaught exception 'Exception' with message 'DateTime::__construct(): Failed to parse time string (13/02/2013) at position 0 (1): Unexpected character' in /test.php:23
Stack trace:
#0 /test.php(23): DateTime-&gt;__construct('13/02/2013')
#1 {main}
  thrown in <b>/test.php</b> on line <b>23</b><br />
[/code]

Which means that only slashes format actually wants you to use American order of date parts.
Hence you should use 'dd-mm-yyyy' or 'mm/dd/yyyy'
Which is weird, and should not be such.

PHP version is 5.4.40
up
2
php at andysdrawings dot co dot uk
10 years ago
DateTime will recognise any number up to 12 as a [month], and any number up to 31 as a [day]; it calculates the resulting date to be [day] days after the start of [month].  This means that when a datetime object is created with more days than are found in that month, the date will be beyond the end of the month.

<?php
  $test
= new DateTime('02/31/2011');
  echo
date_format($test, 'Y-m-d H:i:s'); // 2011-03-03 00:00:00
 
$test = new DateTime('06/31/2011');
  echo
date_format($test, 'Y-m-d H:i:s'); // 2011-07-01 00:00:00
?>
up
1
me at jameswdunne dot com
10 years ago
You should also be aware that DateTime has very lax date validation rules. It appears that all months have a maximum of 31 days.

For example, these will work fine:

<?php
  $test
= new DateTime('02/31/2011');
 
$test = new DateTime('06/31/2011');
?>

We all know that these dates are not real and are invalid so I think a good idea is to do some further validation on dates before creating a DateTime object with them.
up
-1
Andrew
8 years ago
Indeed as mentioned above the constructor for DateTime  will allow the day of month upto 31 to be accepted for all months of the year. You should use checkdate if you wish to check that the day of the month represents a valid gregorian calendar date.
up
-30
tienhm at email dot thinknet dot vn
8 years ago
The construct have some problem with date validate.

When you set
$datetime = DateTime::createFromFormat('Y-m-d H:i:s','2009-02-30 00:00:00');

it will be accepted but convert to 2009-03-02 00:00:00, it means the date was count on and plus 2 days

官方地址:https://www.php.net/manual/en/function.date-create.php

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