-1

Hello i have date format d/m/Y and i like to change it to Y-m-d. i use this code:

$check_in  = '31/12/2014';
$check_out = '2/01/2015';

$md = explode("/", $check_in); // split the array
$nd = $md[2]."-".$md[1]."-".$md[0]; // join them together
$check_in_new = date('Y-m-d', strtotime($nd));

$mmd = explode("/", $check_out); // split the array
$nnd = $md[2]."-".$mmd[1]."-".$mmd[0]; // join them together
$check_out_new = date('Y-m-d', strtotime($nnd));

and its work fine, but if i try to convert 02/01/2015 (year 2015) the result is 2014-01-02 its convert the year to 2014

any help???

Kevin
  • 41,694
  • 12
  • 53
  • 70
pey22
  • 137
  • 2
  • 6
  • 13

2 Answers2

2

I suggest utilize DateTime class in this case, and provide proper format in it with createFromFormat, instead of exploding those strings:

$check_in  = '31/12/2014';
$check_out = '2/01/2015';

$check_in_new = DateTime::createFromFormat('d/m/Y', $check_in);
$check_out_new = DateTime::createFromFormat('d/m/Y', $check_out);

echo $check_in_new->format('Y-m-d') . '<br/>';
echo $check_out_new->format('Y-m-d') . '<br/>';

Ref: http://php.net/manual/en/class.datetime.php

Kevin
  • 41,694
  • 12
  • 53
  • 70
0

If you want to continue the way you are doing right now, you can easily do it by the following way:

$check_in  = '31/12/2014';
$check_out = '2/01/2015';
$check_in_new = implode('-',array_reverse(explode('/',$check_in)));
$check_out_new = implode('-',array_reverse(explode('/',$check_out)));

But there is a better way to do it:

//Set format
$format = 'Y-m-d';
$dto = new DateTime(strtotime($check_in));
$check_in_new = $dto->format($format);
Jubayer Arefin
  • 485
  • 7
  • 17