Convert String to date (european to american) [dup

2019-08-07 07:58发布

问题:

This question already has an answer here:

  • Convert one date format into another in PHP 15 answers

I have a String on the form: "dd/mm-yyyy", where dd is day of the month with two digits, mm is the month represented with two digits, and yyyy is the year with four digits.

I need to store this in my database. Ive tried

$dato = date('d/m-Y' ,strtotime($_POST['dag'] )

But that clearly doesnt work. In my database the date displays as yyyy-mm-dd. How do I properly convert the String to the correct format?

回答1:

strtotime not accept your time string format, so it return false. You can use DateTime::createFromFormat or date_create_from_format, manual here.

DateTime::createFromFormat('d/m-Y', $_POST['dag']);

check the live demo

<?php

var_dump(DateTime::createFromFormat('d/m-Y', '11/01-2017'));

putput:

object(DateTime)#1 (3) {
  ["date"]=>
  string(26) "2017-01-11 14:34:53.000000"
  ["timezone_type"]=>
  int(3)
  ["timezone"]=>
  string(3) "UTC"
}


回答2:

Try to replace the / with a - like so:

$date = "02/04-2016";
$dateNew = str_replace("/","-",$date);


回答3:

You can use DateTime::createFromFormat:

$time = '12/3-1987';
$data = DateTime::createFromFormat('d/m-Y', $time);
echo $data->format('Y-m-d'); //1987-03-12

sandbox