使用php更改日期格式

I want change a date format by php, I have a date in format like this d/m/Y and I want to change to Y-m-d

I have seen this question but for my case, I still get an empty value.

EX:$_REQUEST["date_moc"]='21/07/2014';
I tried to do echo strtotime($_REQUEST["date_moc"]); but nothing to shows up on my screen.

and when I echo date("Y-m-d",strtotime($_REQUEST["date_moc"])); I get 1970-01-01

Any help please,I am really wonder with my code that return empty value like, if possible please tell me with my problem. I am looking forward to see your reply soon!

Thanks!

The simpliest way

$_REQUEST["date_moc"]='21/07/2014';
$explode = explode('/', $_REQUEST["date_moc"]);
list($day,$month,$year) = $explode;
$new_date = "$year-$month-$day";
echo $new_date;

It's very easy just use DateTime::createFromFormat()

$date = DateTime::createFromFormat('d/m/Y', '21/07/2014');
echo $date->format('Y-m-d');

See the live demo on eval.in


For enhancement

You can then also check against invalid input if you extend the snippet above a bit:

if(($date = DateTime::createFromFormat('d/m/Y', '21//2014')) !== false)
    echo $date->format('Y-m-d');
else
    echo 'Invalid format';

But this is only a pattern check which is similar to a regex like

/(\d{1,2})/(\d{1,2})/(\d{4})/

This still allows the user to enter something like:

50/13/2014

To check wether the provided date is valid or invalid check the content of DateTime::getLastErrors(). It will tell you in detail what went wrong. For the example above you'll get something like this:

array(4) {
  ["warning_count"]=>
  int(1)
  ["warnings"]=>
  array(1) {
    [10]=>
    string(27) "The parsed date was invalid"
  }
  ["error_count"]=>
  int(0)
  ["errors"]=>
  array(0) {
  }
}

So according to this information we can extend the snippet again a bit. Which leads us to a result similar like this:

$date = DateTime::createFromFormat('d/m/Y', '50/13/2014')

if($date !== false) {
    $dateLastErrors = $date->getLastErrors();

    if($dateLastErrors['error_count'] > 0 || $dateLastErrors['warning_count'] > 0)
        echo 'Invalid date';
    else
        echo $date->format('Y-m-d');
} else
    echo 'Invalid date format';
}

Which will finally check the date against format an validation.

$date = $_REQUEST["date_moc"];// OR $date ='21/07/2014'; avoid $_REQUEST["date_moc"]='21/07/2014';
echo date('Y-m-d', strtotime($date)); 

Try this :- Working Demo

$date = explode('/',str_replace('-','/',$_REQUEST["date_moc"]));

$updated_date = $date[2].'-'.$date[1].'-'.$date[0];

echo $updated_date;

Simplest way

$date ='21/07/2014';

$date = str_replace("/", "-", $date);

echo date("Y-m-d",strtotime($date));

Working Demo

$_REQUEST["date_moc"]='21/07/2014';
$original_date = explode('/', $_REQUEST["date_moc"]);
$year = $original_date[2]; // 2014
$month = $original_date[1]; // 07
$day =  $original_date[0]; // 21
$date = $year.'/'.$month.'/'.$day;
echo $date;

Demo