如何根据国家更改日期格式


How to change Date format according to the country

我需要根据用户所在国家更改DD/MM/YYYY标签的顺序。

http://en.wikipedia.org/wiki/Date_format_by_country

我想这样做的方式是创建一个国家/日期格式表,并根据国家选择使用jquery移动字段。

是否有一种现有的方法可以在php中甚至在js或更好的方法中完成?我也在寻找一个国家/日期格式的表,而不是手动插入所有的值,但我找不到任何东西…

对于PHP,这应该是一个好的开始:http://php.net/manual/en/function.setlocale.php

对于JavaScript:显示用户's地区格式的日期/时间和时间偏移

总而言之,大多数现代语言都很好地内置了区域设置支持。您不应该自己实现它。这将是令人厌烦的和bug(本地化是困难的)。

如果你使用PHP,那么IntlDateFormatter()可以帮助你:

$d = new DateTime();
$fmt = new IntlDateFormatter('en-US', IntlDateFormatter::SHORT, IntlDateFormatter::NONE);
echo "US: ".$fmt->format($d)."<br/>";
$fmt = new IntlDateFormatter('en-GB', IntlDateFormatter::SHORT, IntlDateFormatter::NONE);
echo "GB: ".$fmt->format($d)."<br/>";
$fmt = new IntlDateFormatter('en-AU', IntlDateFormatter::SHORT, IntlDateFormatter::NONE);
echo "AU: ".$fmt->format($d)."<br/>";
$fmt = new IntlDateFormatter('de-DE', IntlDateFormatter::SHORT, IntlDateFormatter::NONE);
echo "DE: ".$fmt->format($d)."<br/>";
输出:

US: 2/1/18
GB: 01/02/2018
AU: 1/2/18
DE: 01.02.18

如果想在客户端更改日期的格式,可以尝试在JavaScript中的date对象上使用toLocaleString函数。toLocaleString将根据客户端操作系统对其位置的设置更改格式。您也不需要使用国家和日期格式的表。