javascript 将 PHP 日期格式转换为 jQueryUI Datepicker 日期格式

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16702398/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 05:41:32  来源:igfitidea点击:

Convert a PHP date format to a jQueryUI Datepicker date format

phpjavascriptjquery-uijquery-ui-datepickerpyrocms

提问by Tristan Jahier

[EDIT] : I guess people had problem to understand exactly what I mean, so I completely rewrote my explanations.

[编辑]:我想人们很难理解我的意思,所以我完全重写了我的解释。

I work on a project where users can define a date format used in the whole site. It uses PHP date format standard. For example : "year-month-day" is set by "Y-m-d".

我在一个项目中工作,用户可以在其中定义在整个站点中使用的日期格式。它使用 PHP 日期格式标准。例如:“年-月-日”由“Ymd”设置。

PHP standard uses single-character symbols like Y, m, d, F, jto describe the date format. As seen in the documentation : http://www.php.net/manual/fr/function.date.php

PHP 标准使用Y、m、d、F、j等单字符符号来描述日期格式。如文档所示:http: //www.php.net/manual/fr/function.date.php

Sometimes users can select a date thanks to a jQueryUI Datepicker. This component describes its date format with code-words like yy, y, mm, dd, D, ...http://api.jqueryui.com/datepicker/#utility-formatDate

有时用户可以通过 jQueryUI Datepicker 选择日期。此组件使用代码字(如yy、y、mm、dd、D...)描述其日期格式http://api.jqueryui.com/datepicker/#utility-formatDate

I would like to display the dates in the same format for both PHP and the Datepicker. I mean that PHP should output the date as in the format set by user, AND the Datepicker should show the selected date in the same format.

我想为 PHP 和 Datepicker 以相同的格式显示日期。我的意思是 PHP 应该按照用户设置的格式输出日期,并且 Datepicker 应该以相同的格式显示所选日期。

Given that:

鉴于:

  1. The date format is necessarily described "PHP style"
  2. I can't know a priori which format was set by users
  1. 日期格式必须描述为“PHP 风格”
  2. 我无法先验地知道用户设置了哪种格式

/!\ This not a problem of how to read/parse/display a date from a known format.

/!\ 这不是如何从已知格式读取/解析/显示日期的问题。

Unfortunately, Javascript date format description is not the same as in PHP. For instance, these 2 date formats are equivalent but described differently in PHP and Javascript:

不幸的是,Javascript 日期格式描述与 PHP 中的不同。例如,这两种日期格式是等效的,但在 PHP 和 Javascript 中的描述不同:

  1. PHP : Y-m-d (set by users)
  2. Javascript : yy-mm-dd
  1. PHP : Ymd(由用户设置)
  2. Javascript : yy-mm-dd

As you can see, I cannot just configure the datepicker with the PHP date format, because it will be misunderstood, or not recognized at all.

如您所见,我不能只用 PHP 日期格式配置日期选择器,因为它会被误解,或者根本无法识别。

Someone (in answers below) adviced to create my own "date format standard converter", matching each PHP symbol with its equivalent in JS date format description. Just like:

有人(在下面的答案中)建议创建我自己的“日期格式标准转换器”,将每个 PHP 符号与其在 JS 日期格式描述中的等价物相匹配。就像:

  • Y => yy
  • m => mm
  • d => dd
  • y => y
  • z => o
  • ...
  • 是 => 是
  • 米 => 毫米
  • d => dd
  • y => y
  • z => o
  • ...

And then replace each PHP symbol with the JS one. And so "d/m/Y" will be translated into "dd/mm/yy", magically.

然后将每个 PHP 符号替换为 JS 符号。所以“d/m/Y”将被神奇地翻译成“dd/mm/yy”。

But maybe somebody knows another proper way to make jQueryUI Datepicker understand PHP date format standard?

但也许有人知道另一种使 jQueryUI Datepicker 理解 PHP 日期格式标准的正确方法?

EDIT: I wrote a tutorial that explains both the problem and the solution.For further reading : http://tristan-jahier.fr/blog/2013/08/convertir-un-format-de-date-php-en-format-de-date-jqueryui-datepicker

编辑:我写了一个教程,解释了问题和解决方案。进一步阅读:http: //tristan-jahier.fr/blog/2013/08/convertir-un-format-de-date-php-en-format-de-date-jqueryui-datepicker

回答by Tristan Jahier

I chose the brutal method : converting symbol-by-symbol the date format. I made a 'not-so-dummy' code snippet.

我选择了残酷的方法:逐个符号转换日期格式。我制作了一个“不那么虚拟”的代码片段。

/*
?* Matches each symbol of PHP date format standard
?* with jQuery equivalent codeword
 * @author Tristan Jahier
?*/
function dateformat_PHP_to_jQueryUI($php_format)
{
????$SYMBOLS_MATCHING = array(
????????// Day
????????'d' => 'dd',
????????'D' => 'D',
????????'j' => 'd',
????????'l' => 'DD',
????????'N' => '',
????????'S' => '',
????????'w' => '',
????????'z' => 'o',
????????// Week
????????'W' => '',
????????// Month
????????'F' => 'MM',
????????'m' => 'mm',
????????'M' => 'M',
????????'n' => 'm',
????????'t' => '',
????????// Year
????????'L' => '',
????????'o' => '',
????????'Y' => 'yy',
????????'y' => 'y',
????????// Time
????????'a' => '',
????????'A' => '',
????????'B' => '',
????????'g' => '',
????????'G' => '',
????????'h' => '',
????????'H' => '',
????????'i' => '',
????????'s' => '',
????????'u' => ''
????);
????$jqueryui_format = "";
????$escaping = false;
????for($i = 0; $i < strlen($php_format); $i++)
????{
????????$char = $php_format[$i];
????????if($char === '\') // PHP date format escaping character
????????{
????????????$i++;
????????????if($escaping) $jqueryui_format .= $php_format[$i];
????????????else $jqueryui_format .= '\'' . $php_format[$i];
????????????$escaping = true;
????????}
????????else
????????{
????????????if($escaping) { $jqueryui_format .= "'"; $escaping = false; }
????????????if(isset($SYMBOLS_MATCHING[$char]))
????????????????$jqueryui_format .= $SYMBOLS_MATCHING[$char];
????????????else
????????????????$jqueryui_format .= $char;
????????}
????}
????return $jqueryui_format;
}

This function handles all the common codewords between PHP and Datepicker date format standards.

此函数处理 PHP 和 Datepicker 日期格式标准之间的所有常见代码字。

Plus, I added support for character escaping :

另外,我添加了对字符转义的支持:

d m \o\f Ybecomes dd mm 'of' yy

d m \o\f Y变成 dd mm 'of' yy

You may still have problems with symbols like 'W', 'L' that have no equivalent handled by Datepicker.

您可能仍然会遇到诸如“W”、“L”之类的符号的问题,这些符号没有由 Datepicker 处理。

回答by pilsetnieks

You cannot use the same format with datepicker that you're using with PHP.

您不能在日期选择器中使用与 PHP 相同的格式。

Since PHP's date format only uses single letter codes, you're better off just taking the PHP date format and replacing each code to the corresponding value in the jQuery datepicker format, e.g.:

由于 PHP 的日期格式仅使用单字母代码,因此最好采用 PHP 日期格式并将每个代码替换为 jQuery 日期选择器格式中的相应值,例如:

$PHPFormatOptions = array('y', 'Y', 'm', 'd');
$JSFormatOptions = array('yy', 'yyyy', 'mm', 'dd'); // and so on
$JSFormat = str_replace($PHPFormatOptions, $JSFormatOptions, $PHPFormat);

回答by Elias Van Ootegem

Not sure I'm quite with you, but this really shouldn't be an issue. You could either parsethe front-end input: using DateTime::createFromFormatcf. php documentation for this, or use JSON.
Since JSON has an accepted standard way of formatting date strings, you can pass a JSON-stringified version of the input date to PHP, and json_decodeit server-side. Both of these solutions are open to you, though I believe the first one to be easier to implement in your case.

不确定我是否同意你,但这真的不应该成为问题。您可以解析前端输入:使用DateTime::createFromFormatcf. php 文档,或使用 JSON。
由于 JSON 具有格式化日期字符串的公认标准方式,因此您可以将输入日期的 JSON 字符串化版本传递给 PHP,并json_decode在服务器端传递。这两种解决方案都对您开放,但我相信第一个在您的情况下更容易实现。

If you want to be able to choose the format on both sides, the DateTimeobject is definitely what you need:

如果你想两边都可以选择格式,DateTimeobject绝对是你需要的:

$date = new DateTime();
echo $date->format('Y-m-d').' <==> '.$date->format('y-M-j');
$postDate = $date->createFromFormat('y-m-d',$_POST['submitDate']);
echo $postDate->format('Y-m-d');

The format is explained on the page I've linked to.

格式在我链接到的页面上进行了解释。

回答by Anton

Here is the solution:

这是解决方案:

function datepicker_format($format) {
        static $assoc = array(
            'Y' => 'yyyy',
            'y' => 'yy',
            'F' => 'MM',
            'm' => 'mm',
            'l' => 'DD',
            'd' => 'dd',
            'D' => 'D',
            'j' => 'd',
            'M' => 'M',
            'n' => 'm',
            'z' => 'o',
            'N' => '',
            'S' => '',
            'w' => '',
            'W' => '',
            't' => '',
            'L' => '',
            'o' => '',
            'a' => '',
            'A' => '',
            'B' => '',
            'g' => '',
            'G' => '',
            'h' => '',
            'H' => '',
            'i' => '',
            's' => '',
            'u' => ''
        );

        $keys = array_keys($assoc);

        $indeces = array_map(function($index) {
            return '{{' . $index . '}}';
        }, array_keys($keys));

        $format = str_replace($keys, $indeces, $format);

        return str_replace($indeces, $assoc, $format);
    }

The magic double str_replace call caused by duplicating in needles and its replacement values, so that's why the string

由重复针及其替换值引起的神奇双 str_replace 调用,这就是字符串的原因

m/d/Y 

becomes

变成

{{3}}/{{5}}/{{1}}

and after that this nests replacing with actual replacement values:

之后这个嵌套替换为实际替换值:

mm/dd/yy

回答by Robert

Ok so the best solution for you would be to store everything in your website using time();

好的,所以对您来说最好的解决方案是使用 time() 将所有内容存储在您的网站中;

As far as I know datepicker can be set to work with dates for PHP timestamp

据我所知 datepicker 可以设置为使用 PHP 时间戳的日期

dateFormat : 'yy-mm-dd',

Edit :

编辑 :

Why would you store a date like : Y-m-d ? It should be stored as timestamp or int

你为什么要存储这样的日期:Ymd?它应该存储为时间戳或整数