Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get today's timestamp in PHP

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
like image 607
Jiew Meng Avatar asked Jan 22 '11 08:01

Jiew Meng


People also ask

How can I get current timestamp in PHP?

The time() function returns the current time in the number of seconds since the Unix Epoch (January 1 1970 00:00:00 GMT).

How can I get today's date in PHP?

Answer: Use the PHP date() Function You can simply use the PHP date() function to get the current data and time in various format, for example, date('d-m-y h:i:s') , date('d/m/y H:i:s') , and so on.

How do I buy a time stamp today?

Getting the Current Time Stampconst currentDate = new Date(); const timestamp = currentDate. getTime(); In JavaScript, a time stamp is the number of milliseconds that have passed since January 1, 1970.

What does NOW () return in PHP?

MySQL function NOW() returns the current timestamp.


3 Answers

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
like image 78
Salman A Avatar answered Sep 21 '22 23:09

Salman A


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'));
like image 40
lonesomeday Avatar answered Sep 22 '22 23:09

lonesomeday


Today's start timestamp

$todayStartTS = strtotime(date('Y-m-d', time()) . ' 00:00:00');
like image 45
Mircea Voivod Avatar answered Sep 21 '22 23:09

Mircea Voivod