PHP's DateTime object and unix times..

Just started checking out PHP 5.2's DateTime object. Its great to have a 'standard object' for dates.. Lots of the frameworks out there all define their own date class, perhaps this can help creating more generic interfaces.

Its quite hard to find the documentation though. I'm looking for a way to create a DateTime object based on a unix time, but this seems to be the only way:

  1. <?php
  2.  
  3. // unix time
  4. $unix = time();
  5.  
  6. $dateTime = new DateTime(date(DATE_ATOM,$unix));
  7.  
  8. ?>

Which is a pretty nasty hack, because the strtotime()-like parsing is unnecessary because the actual date is likely stored as a number anyway..

Update: kore pointed out the proper way to do this in the comments.


2 Responses to PHP's DateTime object and unix times..

  1. 33 kore 2007-10-20 6:10 pm

    Just use:

    $time = new DateTime( '@123456789' );
    ?>

  2. 34 mathieu Kooiman 2007-10-21 5:20 am

    Hi Evert,

    I wrote a little (dutch) article on the DateTime extensions on my own blog:

    http://www.scriptorama.nl/tips-tricks/php-52-de-date-extensie-uitbreidingen .

    I missed this little feature, so I've added it :). Thanks

Leave a Reply



About

My name is Evert, and I've been writing semi-regularly on this blog since 2006.

I'm currently available for contract work.

more info.

Subscribe

Dropbox

Dropbox is a simple cross-platform online backup and sync application. The first 2GB of space is free, and both you and me get an extra 250MB extra space if you sign up through this link.