How can I get today's timestamp in PHP

59,622

Solution 1

You can call ->setTime(0, 0) to zero out the time portion:

$date = DateTime::createFromFormat('Y-m-d', '2011-01-22')->setTime(0, 0);
echo $date->format('d M Y g:i:s a');
// 22 Jan 2011 12:00:00 am

Solution 2

See the documentation for DateTime::createFromFormat:

If format does not contain the character ! then portions of the generated time which are not specified in format will be set to the current system time.

If you do the following function call, you'll get the result you expect:

$dtToday = DateTime::createFromFormat('!Y-m-d', date('Y-m-d'));

Solution 3

Today's start timestamp

$todayStartTS = strtotime(date('Y-m-d', time()) . ' 00:00:00');

Solution 4

You can do this by passing the current unix timestamp as the second parameter to the date function

echo date("Y-m-d H:i:s",time());

Solution 5

Remove this part g:i:s a from your code.

Now, if you want a nice date formatted according to your local, i recommand you to use strftime() function.

Share:
59,622
Jiew Meng
Author by

Jiew Meng

Web Developer & Computer Science Student Tools of Trade: PHP, Symfony MVC, Doctrine ORM, HTML, CSS, jQuery/JS Looking at Python/Google App Engine, C#/WPF/Entity Framework I hope to develop usable web applications like Wunderlist, SpringPad in the future

Updated on July 20, 2021

Comments

  • Jiew Meng
    Jiew Meng almost 3 years

    I tried

    $dtToday = DateTime::createFromFormat('Y-m-d', date('Y-m-d'));
    

    but when I output it

    die($dtToday->format('d M Y g:i:s a'));
    

    I still get the time eg "22 Jan 2011 4:53:59 pm". Why is that?

    UPDATE

    Ah... many people misunderstood me, my bad, I forgot to point out the main point. I created the date with just the date portion, I don't want the time. So I'd expect something like

    22 Jan 2011 12:00:00 am
    
  • user4959001
    user4959001 over 13 years
    the second parameter to date() defaults to time(), so date('Y-m-d') is sufficient.
  • Jiew Meng
    Jiew Meng over 13 years
    actually its not the format, see my update. Basically I am asking why after creating the DateTime with just the date minus the time part, why do I still get the time? I want the date without the time portion
  • Jiew Meng
    Jiew Meng over 13 years
    Sorry, I mean why after creating the DateTime without the time portion, why do I still get the time?
  • Jiew Meng
    Jiew Meng over 13 years
    Sorry, I mean why after creating the DateTime without the time portion, why do I still get the time?
  • Gökhan Mete ERTÜRK
    Gökhan Mete ERTÜRK over 7 years
    it should be ' 00:00:00' Don't forget the space.