【问题标题】:Function to change JS date format to PHP将JS日期格式更改为PHP的函数
【发布时间】:2014-03-17 10:14:57
【问题描述】:

我正在尝试将 javascript 日期格式(例如“dd/mm/yy”)转换为 PHP 等效格式(例如“d/m/Y”)。这适用于 jQuery datepicker UI。

我找到了一个函数(未经测试)可以反过来做,here

我把它改了一下,看起来像这样:

function dateFormat(){

    $pattern = array(

        //day
        'dd',
        'd',
        'DD',
        'o',

        //month
        'MM',
        'M',
        'mm',
        'm',

        //year
        'yy',
        'y'
    );
    foreach($pattern as &$p)
    {
        $p = '/'.$p.'/';
    }

    $replace = array(

        //day
        'd',        //day of the month
        'j',        //3 letter name of the day
        'l',        //full name of the day
        'z',        //day of the year

        //month
        'F',        //Month name full
        'M',        //Month name short
        'm',        //numeric month leading zeros
        'n',        //numeric month no leading zeros

        //year
        'Y',        //full numeric year
        'y'     //numeric year: 2 digit
    );

    return preg_replace($pattern, $replace, 'dd/mm/yy');
}

但是,我得到的不是预期的“d/m/Y”,而是“j/n/Y”。我认为它会按顺序进行替换;即在 d 之前找到 dd 并首先替换它。怎么回事?

谢谢。

【问题讨论】:

  • 请注意,我已硬编码“dd/mm/yy”用于测试目的。
  • 最好的方法可能是使用 DateTime::createFromFormat。
  • JavaScript 没有日期格式代码...
  • 对不起,它是在 jQuery 的 datepicker ui 中使用的。我会将其添加到最初的问题中。
  • @CasimiretHippolyte 谢谢,但我正在尝试转换格式字符串,而不是实际日期。

标签: javascript php regex date


【解决方案1】:

您可以将 strtr 与关联数组一起使用(您必须完成它):

$trans = array('dd' => 'd',
               'mm' => 'm',
               'yy' => 'Y',
               'd'  => 'j');

$phpDateFormat = strtr($datePickerFormat, $trans);

注意,2个字符序列必须在数组的开头。

【讨论】:

  • 谢谢,我会测试一下
猜你喜欢
  • 1970-01-01
  • 2023-02-03
  • 1970-01-01
  • 2012-08-07
  • 1970-01-01
  • 2017-09-04
  • 2022-07-04
  • 1970-01-01
相关资源
最近更新 更多