php - 允许 PHP date() 函数识别 dd-mm-yy 格式

标签 php regex date

我希望稍微修改 PHP date() 函数,以便它识别 dd/mm/yy 或 dd-mm-yy 的英国 6 位格式。可以理解,它会认为采用这种形式的日期是国际 (yy-mm-dd) 格式。

我仍然希望将它传递给日期函数,因为这将允许它识别其他格式,但由于我住在英国,人们很可能会将其放入英国格式。

有什么想法吗?我怀疑 Regex 参与了这个问题的解决方案......

更新——我的解决方案

使用下面答案中的部分,这就是我在 dd/mm/yy 的情况下能够更改它的方式:

$s_date = str_replace('/', '-', $s_date);

preg_match('^(.*)[-](.*)[-](.*)$^', $s_date, $matches);
if ($matches) {
    if (strlen($matches[3]) == 2) {
        $matches[3] = '20'.$matches[3];
    }
    $s_date = $matches[1].'-'.$matches[2].'-'.$matches[3];
}

最佳答案

此函数将允许您检查 dd-mm-yy 和 dd/mm/yy。

通过使用 str 替换 - 您强制日期始终采用 'dd-mm-yy' 格式。 strtotime 将带有“-”的日期解释为您想要的格式。

// Is this a valid date?
    function valid_date($str) 
    {
        $str = str_replace('/', '-', $str);
        if ($arr = strtotime($str))
        {
            $arr = explode("-", date("d-m-Y", strtotime($str)));
            $yyyy = $arr[2];
            $mm = $arr[1];
            $dd = $arr[0];
            if (is_numeric($yyyy) && is_numeric($mm) && is_numeric($dd))
            {
                return checkdate($mm, $dd, $yyyy);
            }
        }
        return false;
    }

Quote from strtotime:

if the separator is a slash (/), then the American m/d/y is assumed; whereas if the separator is a dash (-) or a dot (.), then the European d-m-y format is assumed.

关于php - 允许 PHP date() 函数识别 dd-mm-yy 格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12932115/

相关文章:

php - PDO 查询有问题

ruby - 将 ruby​​ 正则表达式定义转换为 python 正则表达式

java.util.Calendar getMaximum 最后一天返回错误

javascript - 根据地区返回不同的日期

php - 使用 jQuery 向 PHP 发送 PUT AJAX 请求时出现错误 405 方法不允许

php - Magento - 拉一个单一的客户评论

php - 有没有办法在没有插件的情况下在结帐完成前上传图片?

c# - 单个正则表达式去除除 anchor 之外的所有 HTML

regex - 用perl分割一个带有多个空格的字符串?

java - SimpledateFormat的parse方法java