toLocaleDateString() short format
我想使用Date.toLocaleDateString()的短记号,但是要使用本地格式。有很多解决方案可以对yyyy-mm-dd格式进行硬编码,但是我希望它依赖于托管页面的系统。到目前为止,这是我的功能:
1 2 3 4 5 6 | function getDate(dateTimeString) { var date = getDateTime(dateTimeString); var options = { year:"numeric", month:"numeric", day:"numeric" }; return date.toLocaleDateString( date.getTimezoneOffset(), options ); } |
但是它会这样返回:2015年1月28日,星期三,我不想要。有任何建议/想法吗?
PS:它不是浏览器,使用它的人很可能没有网络连接。所有信息都是从本地数据库获取的,所以我不能使用任何像这样的狂热东西如何使用javascript地理位置来获取访问者的位置(即国家/地区)。
我认为toLocaleDateString函数使用设备上的默认本地数据。
尝试以下代码检查输出:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | // America/Los_Angeles for the US // US English uses month-day-year order console.log(date.toLocaleDateString('en-US')); // →"12/19/2012" // British English uses day-month-year order console.log(date.toLocaleDateString('en-GB')); // →"20/12/2012" // Korean uses year-month-day order console.log(date.toLocaleDateString('ko-KR')); // →"2012. 12. 20." // Arabic in most Arabic speaking countries uses real Arabic digits console.log(date.toLocaleDateString('ar-EG')); // →"???/???/????" // chinese console.log(date.toLocaleDateString('zh-Hans-CN')); // →"2012/12/20" |
请注意,NodeJS将仅以设备的语言环境格式提供,因此当您为LocaleDateString指定参数时,例如:
1 2 | new Date("1983-March-25").toLocaleDateString('fr-CA', { year: 'numeric', month: '2-digit', day: '2-digit' }) '03/25/1983' |
请注意,您希望" fr-CA"给您YYYY-MM-DD,但没有。那是因为自从我的Node实例在美国语言环境中运行以来,它只使用美国语言环境。
实际上有一个关于Node github帐户的错误报告,描述了问题和解决方案:
https://github.com/nodejs/node/issues/8500
提供的解决方案是安装
您可以尝试以下操作:
1 2 | var date = new Date(Date.UTC(2015, 0, 28, 4, 0, 0)); console.log(date.toLocaleDateString("nl",{year:"2-digit",month:"2-digit", day:"2-digit"})); |
至少我在Chrome(48.0.2564.116)中给了我" 28-01-15"。
Firefox仅返回" 01/28/2015",而phantomJS返回" 28/01/2015",而不考虑语言环境。
是的。它非常简单。您可以按以下方式使用日期对象:
1 2 3 4 | var d = new Date(); var mm = d.getMonth() + 1; var dd = d.getDate(); var yy = d.getFullYear(); |
然后,您应该具有所需的数字,可以使用所需的任何格式来组成字符串。
1 | var myDateString = yy + '-' + mm + '-' + dd; //(US) |
请注意,如果数字是单个数字,这将给出类似于2015-1-2的信息,如果您需要2015-01-02,则需要进一步转换。
还请注意,这只会给出"客户"日期,即。用户系统上的日期。这应该在当地时间。如果需要服务器时间,则必须具有某种api来调用。
日期:
完整月份:
短短一个月:
全天:
简而言之:
显然,Date.prototype.toLocaleDateString()在各个浏览器中不一致。您可以实现短日期格式的不同变体,如下所示:
关于浏览器文化,JavaScript日期的格式如何?