简体   繁体   中英

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

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

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'));

今天的开始时间戳

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

您可以通过将当前的 unix 时间戳作为第二个参数传递给 date 函数来做到这一点

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

Remove this part g:i:sa from your code.

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

You are getting "22 Jan 2011 4:53:59 pm" because those are the rules you format your date with :
d (day) : 22
M (Month) : Jan
Y (Year) : 2011
g (12-hour format) : 4
i (minutes): 53
s (seconds): 59
a (am/pm): pm
Be more speciffic about the format would you like your timestamp to have. I suggest you take a peak at the php date documentation.

Is it using UTC, or something?

I have a PHP version that gives me an error whenever I do something date related without first using date_default_timezone_set . Maybe that'll help you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM