DateTime :: CreateFromFormat for PHP 5.2.14 [英] DateTime::CreateFromFormat for PHP 5.2.14

查看:113
本文介绍了DateTime :: CreateFromFormat for PHP 5.2.14的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用以下代码将用户输入转换为mysql时间戳。

I am using the following code to convert user input into a mysql timestamp.

$datetime = DateTime::createFromFormat('m/d/Y g:i a', "{$exp}");
$timestamp = $datetime->format('Y-m-d H:i:s');

其中 $ exp 将等同于: 06/12/2013 6:41 pm

where $exp would equal something like: 06/12/2013 6:41 pm

在本地运行PHP 5.4.3的服务器上运行正常,但是当我将相同的脚本上传到我的托管服务器,它不想运行这个部分可能是因为PHP版本的差异。

This works fine on my local server which is running PHP 5.4.3, but when I upload the same script onto my hosting server, It does not want to run this part probably because of the difference in PHP versions.

我该如何解决这个问题?谢谢!

How would I go about fixing this or an alternative to it? Thanks!

推荐答案

您可以扩展DateTime类并实现 createFromFormat()你自己这样: -

You could extend the DateTime class and implement createFromFormat() yourself like this:-

class MyDateTime extends DateTime
{
    public static function createFromFormat($format, $time, $timezone = null)
    {
        if(!$timezone) $timezone = new DateTimeZone(date_default_timezone_get());
        $version = explode('.', phpversion());
        if(((int)$version[0] >= 5 && (int)$version[1] >= 2 && (int)$version[2] > 17)){
            return parent::createFromFormat($format, $time, $timezone);
        }
        return new DateTime(date($format, strtotime($time)), $timezone);
    }
}

$dateTime = MyDateTime::createFromFormat('Y-m-d', '2013-6-13');
var_dump($dateTime);
var_dump($dateTime->format('Y-m-d'));

这将适用于所有版本的PHP> = 5.2.0。

This will work in all versions of PHP >= 5.2.0.

参见此处演示 http://3v4l.org/djucq

这篇关于DateTime :: CreateFromFormat for PHP 5.2.14的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆