mktime() in PHP is giving me the wrong year when included in a date() function

StackOverflow https://stackoverflow.com/questions/15466212

  •  24-03-2022
  •  | 
  •  

Pergunta

This one is killing me.

I'm trying to write a tiny function that simple outputs the date two days from now. I'm using the following code (in PHP emulator) to try to get it working:

echo date('d/m/Y', mktime(0, 0, 0, date("d")+2, date("m"), date("Y")));

The output I get is 03/07/2014, clearly the wrong date (I expect to get 03/17/2014).

What's killing me is that when I try

echo date("Y");

I get the correct output, 2013.

What is happening inside the date function that is ruining my code?

Foi útil?

Solução

You have the day and month parameters to mktime() backwards:

int mktime ([ int $hour = date("H") [, int $minute = date("i") [, int $second = date("s") [, int $month = date("n") [, int $day = date("j") [, int $year = date("Y") [, int $is_dst = -1 ]]]]]]] )

So, you are looking for:

echo date('d/m/Y', mktime(0, 0, 0, date("m"), date("d") + 2, date("Y")));

Outras dicas

There are easier ways to do this. DateTime makes working with dates easier than mktime() and date().

$now = new DateTime();
$now->modify('+2 days');
$two_days = $now->format('m/d/Y');

See it in action

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top