【问题标题】:String to time returning empty字符串到时间返回空
【发布时间】:2017-01-11 00:59:20
【问题描述】:

我有一个函数可以从用户日期输入中去除斜线,使其格式为ddmmYYYY 格式。

function mydate($input)
{
    $sanitized = preg_replace("/[^0-9A-Za-z\:\- ]/", "", $input);
    return $sanitized;
}

我有另一个函数可以检查日期是否在该日期之前

function datebefore($before,$after)
{

    $before = substr($before,2,2)."-".substr($before,0,2)."-".substr($before,4,4);
    $after = substr($after,2,2)."-".substr($after,0,2)."-".substr($after,4,4);


    return strtotime($after)." > ".strtotime($before) ; 

    /* if(strtotime($after) < strtotime($before) )
    {
        return "The start date is after the end";
    } */
}

我遇到的问题是,当之前或之后日期比当前日期早 1 天时,它返回一个空字符串而不是时间戳

【问题讨论】:

    标签: php string datetime strtotime


    【解决方案1】:

    strtotime 取决于分隔符来决定您使用的日期格式。

    如果分隔符是-,则采用合理的日期格式dd/mm/yyyy,如果是/,则采用美国日期格式mm-dd-yyyy

    所以你的问题是你使用的分隔符。把格式改成dd-mm-yyyy,重新整理一下你的d、m、y值的顺序就好了

    function datebefore($start,$end)
    {
    
        $s = sprintf('%s-%s-%s',  substr($start,0,2), substr($start,2,2), substr($start,4,4));
        $e = sprintf('%s-%s-%s', substr($end,0,2), substr($end,2,2), substr($end,4,4));
    
        return strtotime($s) > strtotime($e) 
                    ? 'The start date is after the end' 
                    : 'The start date is before the end'; 
    }
    
    function mydate($input)
    {
        $sanitized = preg_replace("/[^0-9A-Za-z\:\- ]/", "", $input);
        return $sanitized;
    }
    
    $s = mydate('10/12/2016');
    echo $s . PHP_EOL;
    $e = mydate('06/12/2016');
    echo $e . PHP_EOL;
    
    $c = datebefore($s, $e);
    echo $c;
    

    【讨论】:

      【解决方案2】:

      因为strtotime不接受你的时间字符串格式,所以返回false。

      你可以使用DateTime::createFromFormat替换strtotime来创建日期时间,然后使用运算符>进行比较。

      作为:

      var_dump(DateTime::createFromFormat('dmY', '11012017'));
      

      【讨论】:

      • 在 SO 上不鼓励仅链接答案
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-01-27
      • 2020-07-11
      • 2015-05-25
      • 2011-05-09
      相关资源
      最近更新 更多