Convert String to date (european to american) [duplicate]

[亡魂溺海] 提交于 2019-12-11 07:34:54

问题


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



来源:https://stackoverflow.com/questions/41571263/convert-string-to-date-european-to-american

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!