我很奇怪strtotime行为 [英] I'm weird with strtotime behaviour

查看:144
本文介绍了我很奇怪strtotime行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用jquery datepicker插件获取了From日期和To date。以下是POST的输出。

I am getting the From date and To date using jquery datepicker plugin. The following is the output of POST.

Array (
    [fromDate] => 01/03/2012
    [toDate] => 15/03/2012
    [hdnDownload] => Download
) 

我正在尝试将此日期格式转换为其他日期格式:

I am trying to convert this date format to another date format like this:

echo'fromdate'.$fromDate = date("Y/n/j", strtotime($_POST['fromDate']));
echo'todate'.$toDate = date("Y/n/j", strtotime($_POST['toDate']));

它给出以下输出:

fromdate: 2012-1-3
todate:1969-12-31

fromDate是好的,但是ToDate已经改变了,可以帮助我吗?

The fromDate is fine but the ToDate has changed, can you please help me.

推荐答案

需要确保您得到正确的结果是 DateTime :: createFromFormat() if您使用PHP> = 5.3.0或 strptime()与PHP > = 5.1.0,您可以在其中指定输入格式。

What you need to make sure you get correct result is either DateTime::createFromFormat() if you're using PHP >= 5.3.0, or strptime() with PHP >= 5.1.0, where you can specify input format.

尽管如果您仍然想允许自由格式,您可能想要制作拐杖,正则表达式为这种特定格式,并使用其中一个仅适用于美国m / d / Y,如下所示:

Although if you still want to allow free format there you might want to make a crutch, that would check with regex for this particular format and use one of these only for american m/d/Y, something like:

function parsedate($date) {
    if (preg_match('#\d{1,2}/\d{1,2}/\d{2,4}#', $date)) {
        $parsed = strptime($date, '%m/%d/%Y');
        return mktime(0, 0, 0, $parsed['tm_mon'], $parsed['tm_mday'], 1900+$parsed['tm_year']);
            // 'tm_year' is years since 1900
    } else {
        return strtotime($date);
    }
}

它还是拐杖,但我看不到任何更清洁的方式。

It's still a crutch, but I can't see any cleaner way.

这篇关于我很奇怪strtotime行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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