开发者

How can I get today's timestamp in PHP

I tried

$dtToday = DateTime::createFromForma开发者_如何学Got('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'));


Today's start timestamp

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


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


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜