简体   繁体   English

PHP中的日期格式更改

[英]Date format change in php

I've the date format 12/May/2018. 我的日期格式为12 / May / 2018。 I need to change it to 2018-12-05.Please help me. 我需要将其更改为2018-12-05。请帮助我。

$originalDate = "12/May/2018";
$newDate = date("Y-m-d", strtotime($originalDate));
echo $newDate;

Output: 1969-12-31 输出:1969-12-31

Thanks in advance. 提前致谢。

Use this code : 使用此代码:

$originalDate = "12/May/2018";
$originalDate =str_replace("/", " ", $originalDate);
$newDate = date("Y-m-d", strtotime($originalDate));
echo $newDate;

There's no need for any manual parsing. 无需任何手动解析。
You should use PHP's DateTime class, which is much more flexible than the old date() -function. 您应该使用PHP的DateTime类,它比旧的date()函数灵活得多。

Here's an example that does what you want: 这是一个满足您需求的示例:

$date = DateTime::createFromFormat('d/M/Y', '12/May/2018');
echo $date->format('Y-m-d');

Demo: https://3v4l.org/Y5HF0 演示: https//3v4l.org/Y5HF0

That date format is not supported by strtotime. strtotime不支持该日期格式。
But replacing the / with space is a supported format. 但是用空格替换/是受支持的格式。

$originalDate = "12/May/2018";
$newDate = date("Y-m-d", strtotime(str_replace("/", " " ,$originalDate)));
echo $newDate;

https://3v4l.org/K8cOF https://3v4l.org/K8cOF

The reason you get 1969-12-31 is because UNIX 0 is 1970-01-01 00:00:00. 您得到1969-12-31的原因是因为UNIX 0为1970-01-01 00:00:00。
When strtotime can't parse the date it returns false . 当strtotime无法解析日期时,它将返回false
False can be typeconverted to 0 . False可以类型转换为0
That means date reads it as "Ymd" at UNIX time 0 (1970), and because of your timezone you get 1969-12-31. 这意味着date在UNIX时间0(1970)时将其读取为“ Ymd”,并且由于您的时区,您将获得1969-12-31。

try this, 尝试这个,

$originalDate = "12/May/2018";
$newDate = date_format(date_create_from_format("j/F/Y", $originalDate), 'Y-m-d');
echo $newDate; 

Note : if your day format is 01 use d , if 1 use j 注意:如果你一天格式01使用d ,如果1使用j

The output is: 2018-05-12 输出是:2018-05-12

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM