简体   繁体   English

如何在php中转换日期格式

[英]How convert date format in php

hello guys i have date like this 大家好,我有这样的约会

25 March 2014 - 16:45

i want to convert this date in to this format how to do that please Help 我想将此日期转换成这种格式,该怎么做,请帮助

2014-03-25 16:45:00

i try this $creation = date('Ymd H:i:s',strtotime('25 March 2014 - 16:45')); 我尝试这个$creation = date('Ymd H:i:s',strtotime('25 March 2014 - 16:45')); but it's not work 但这是行不通的

i try this $creation = date('Ymd H:i:s',strtotime('25 March 2014 - 16:45')); 我尝试这个$creation = date('Ymd H:i:s',strtotime('25 March 2014 - 16:45')); but it's not work 但这是行不通的

The reason your code doesn't work is because '25 March 2014 - 16:45' is not in a format that strtotime() can parse. 您的代码无法正常运行的原因是因为“ '25 March 2014 - 16:45'格式不是strtotime()可以解析的格式。

strtottime() is good at handling a wide range of formats, but it can't cope with absolutely anything; strtottime()擅长处理各种格式,但是它不能应付任何事情。 there's just too much variation possible. 可能会有太多变化。

I suggest that you try PHP's DateTime class instead. 我建议您改用PHP的DateTime类。 This class has a method called createFromFormat() which allows you to specify the format of the incoming date string. 此类具有一个名为createFromFormat()的方法,该方法使您可以指定传入日期字符串的格式。 This makes it easier for it to parse, and allows for formats that might not be recognised otherwise, like yours. 这使其更易于解析,并允许使用其他格式无法识别的格式,例如您的格式。

Try this: 尝试这个:

$date = DateTime::createFromFormat('j F Y - H:i', '25 March 2014 - 16:45');
echo $date->format('Y-m-d H:i:s');

Use PHP DateTime 使用PHP DateTime

You have "-" in "25 March 2014 - 16:45" in the string so it not be able to read by DateTime 字符串中的“ 2014年3月25日-16:45”中包含“-”,因此DateTime无法读取

So work around would be 所以要解决

$str = "25 March 2014 -16:45";

$date = new DateTime(str_replace("-","",$str));
echo $date->format('Y-m-d H:i:s');

I've successfully tried the following with your string: 我已经使用您的字符串成功尝试了以下操作:

$a = strptime('25 March 2014 - 16:45', '%d %B %Y - %R');
$time = mktime(
    $a["tm_hour"],
    $a["tm_min"],
    $a["tm_sec"],
    $a["tm_mon"]+1,
    $a["tm_mday"],
    $a["tm_year"]+1900
);
$converted = date('Y-m-d H:i:s',$time);

尝试这个:

$creation = date('Y-m-d H:i:s',strtotime('25 March 2014 16:45'));

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

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