PHP
downloads | documentation | faq | getting help | mailing lists | reporting bugs | php.net sites | links | conferences | my php.net

search for in the

date_date_set> <checkdate
Last updated: Mon, 26 Nov 2007

view this page in

date_create

(PHP 5 >= 5.1.0)

date_create — Returns new DateTime object

说明

DateTime date_create ([ string $time [, DateTimeZone $timezone ]] )
DateTime DateTime::__construct ([ string $time [, DateTimeZone $timezone ]] )

参数

time

String in a format accepted by strtotime(), defaults to "now".

timezone

Time zone of the time.

返回值

Returns DateTime object on success or FALSE on failure.



date_date_set> <checkdate
Last updated: Mon, 26 Nov 2007
 
add a note add a note User Contributed Notes
date_create
Anonymous
28-Apr-2008 09:38
Here's a way to use the DateTime object to validate user submitted date inputs:

<?php
   
class DateTimeException extends Exception {
        public function
__construct ($message, $errornumber = NULL) {
           
parent::__construct($message, $errornumber);
        }
       
        public function
__toString() {
            return (
"Error: $this->message");
        }
    }

    class
MyDateTime extends DateTime {
           
        public function
__construct($input) {
            if (
strtotime($input)) {
               
parent::__construct($input);
            }
            else {
               
$this->is_valid_date = FALSE;
                throw new
DateTimeException("Date (" . $input . ") is incorrect");
            }
        }
       
        public function
isValidDate() {
            return
$this->is_valid_date;
        }
    }

    try {
       
$date = new DateTime("Not a date")
    }
    catch (
DateTimeException $error) {
        echo
$error;
        exit;
    }
?>

Comments are very much appreciated
prikkeldraad at gmail dot com
19-Feb-2008 09:56
Serialization and unserialization fail for the DateTime object (PHP 5.2.5).

With your own __sleep and __wakeup function in a child class you can work around this problem.

<?php
class MyDateTime extends DateTime {
    private
$_str;
   
    public function
__sleep(){
       
$this->_str = $this->format('c');
        return array(
'_str');
    }
   
    public function
__wakeup() {
       
$this->__construct($this->_str);
    }
}
?>

Regards, Mick
mike at eastghost dot com
06-Feb-2008 04:16
Documentation on the DateTime object is sparse.  Here's a good tutorial:

http://laughingmeme.org/2007/02/27/
looking-at-php5s-datetime-and-datetimezone/
mroximoron
11-Dec-2007 11:15
The string format here is a bit wrong, yes it accepts the same format, but not the same range as strtotime.

strtotime can't handle dates like 2100-01-01 while this one can..
jsnell at e-normous dot com
29-Oct-2007 07:22
When using these functions inside of destructors or functions called as a result of being registered with register_shutdown_handler, be sure to use date_create() instead of new DateTime().  This is because new DateTime will throw an exception on failure, which is not permitted in any of the above circumstances.  If new DateTime() does fail in one of these circumstances, you will get an error stating "Fatal error: Exception thrown without a stack frame in Unknown on line 0."
karsten at typo3 dot org
18-Sep-2007 12:03
The manual says "Returns DateTime object on success or FALSE on failure".

I tried hard to provoke a failure, but I seem to always get a DateTime object back, even though the PHP log says things like: "Failed to parse time string (2007W992-11:16:47+00:00) at position 5 (9): Unexpected character"

So if you (need to) check the result, beware!

[red. in PHP 5.3 and higher, you can do that with DateTime::getLastErrors().]
Dok
05-Jul-2007 10:52
If you want to create the DateTime object directly from a timestamp use this

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

See also: http://bugs.php.net/bug.php?id=40171
artur at jedlinski dot pl
19-Apr-2007 08:47
"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
?>
]
nizar dot jouini at gmail.com
07-Mar-2007 09:05
date_create and other DateTime related functions are included by default only in PHP versions equal and greater than 5.2.

In PHP 5.1.2 this functionality is marked to be experimental and has to be enabled at compile time.

date_date_set> <checkdate
Last updated: Mon, 26 Nov 2007
 
 
show source | credits | sitemap | contact | advertising | mirror sites