简体   繁体   中英

PHP date function usage that I don't understand

So I have been handed a WordPress site that was built by other devs and I'm in the process of figuring out how much of the customization works. I've come across their function for archiving posts and I've encountered a use of the PHP date() function that I've never seen before (though admittedly, I haven't seen a whole lot)

date('Y-1-1', strtotime('-1 year'))

Can someone explain that bit of it to me? I've never seen the parameter 'Y-1-1' before and I wasn't even aware you could pass other params to the date() function like that. I played with the parameters a bit and I either see no change or I break it.

Thanks (again)!

Just look at the output:

echo date('Y-1-1', strtotime('-1 year'));
// 2012-1-1

and the documentation:

http://php.net/manual/de/function.date.php

http://php.net/manual/de/function.strtotime.php

  • Y is the key for the year with four digits.
  • -1-1 are just normal characters, ignored by date function
  • -1 year gives the timestamp of now - 1 year, so the year is 2012

That call will return last year's first of January: assuming today's date 2013-12-27 this will give

  1. strtotime('-1 year') resolves to today's date one year ago, ie 2012-12-27
  2. everything that date doesn't recognize as a format element is interpreted literally (from the documentation : Unrecognized characters in the format string will be printed as-is. ), so the format string is converted to 2012-1-1

The strtotime function returns a unix timestamp after parsing the supplied string, which in this example gives us the timestamp for the current time, but in the previous year.

The date function, then, formats this timestamp according to the format: Y-1-1 , which effectively outputs the four digit year in place of Y , and outputs the 1 s literally.

So, the complete code: date('Y-1-1', strtotime('-1 year')) returns the string 2012-1-1 if run this year is 2013 , which it is.

References:

Here is the output from the interactive shell:

~/Code $ php -a
Interactive shell

php > echo strtotime('-1 year');
1356628992
php > echo date('Y-1-1', 1356628968);
2012-1-1
php >

'Y-1-1' basically means the same as 'Current Year-1-1', so it would be 2013-1-1 (1st January of 2013'. Date's function first argument can contain any characters or formatting characters, that might be found here: PHP Date

Second parameter is timestamp (UNIX timestamp which is amount of seconds passed from 1st January of 1970). strtotime('-1 year') gives you timestamp in 1 year before this year.

The result would be '2012-1-1'. This code listing basically gives you 1st January of previous year as result.

date('Y-1-1', strtotime('-1 year')); // 2012-1-1

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