Pergunta

I'm to write a function that will return a specific day if it's between two dates... I've been trying to use mktime, but it keeps returning December?

Essentially, I'm trying to do this:

$now = date('F d, Y');

if($now [is Between July of last year and January of next year] ) {

  //Output last day of January in this year

} elseif($now [is Between January of this year and July of this year]) {

  //Output last day of July for next year

}

I'm a little confused on whether I need to be using mktime or strtotime? To determine January of next year, I tried below, but it returned December, 2012?

$jan = date("F,Y", mktime(0, 0, 0, 1, 0, $year+1));
Foi útil?

Solução

Day 0 of January 2012 is actually December 31st of 2011.

PHP's months are 1-based. Try

$jan = date("F,Y", mktime(0, 0, 0, 1, 1, $year+1));
                                      ^--- 1st, not 0th

instead.

Outras dicas

The day parameter should be 1 instead of 0. See http://php.net/manual/en/function.mktime.php for details.

date("F,Y", mktime(0, 0, 0, 1, 1, $year+1));

The day param in mktime should be 1 instead of 0:

mktime(0, 0, 0, 1, 1, $year+1);

Otherwise it will think it's "January 0th", which gets translated to "January 1st minus 1 day" = "December 31 from the previous year".

You can actually use this behaviour to add and substract days (or anything really) to dates, like this:

mktime(0, 0, 0, 1, 67, 2012); //returns the correct date for the 67th day of 2012
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top