我需要一个 JavaScript 日期/时间格式如下:
2015 年 2 月 16 日上午 06:31:00
我本来打算使用 toLocaleTimeString
和一些选项,但我在下面尝试的代码似乎在 Chrome 中不起作用。
function getFormattedDateTime(dateTimeToFormat) {
dateTimeToFormat = new Date(dateTimeToFormat);
var monthOptions = {
month: 'long', year: 'numeric', day: 'numeric',
hour: '2-digit', minute: '2-digit', second: '2-digit'
};
return dateTimeToFormat.toLocaleTimeString('en-us', monthOptions);
}
上述代码的输出是2015年2月16日上午6:31
很接近,但没有雪茄。 如果 jQuery 有更好的日期格式化实用程序,那么它也是一个选择。仅限 jQuery,请不要使用插件。
这里有一个 JSFiddle 可以节省一些时间:https://jsfiddle.net/gxze230b/
经过拼写错误更正后,输出字符串现在为:2015 年 2 月 16 日上午 6:31:00
最佳答案
您的代码中有一个拼写错误..
而不是秒:'2位数字'
它应该是秒:'2位数字'
更新了你的 fiddle https://jsfiddle.net/gxze230b/3/
编辑:寻找一段时间后认为最好使用此处给出的答案
Where can I find documentation on formatting a date in JavaScript?
目前似乎并不支持所有组合。
关于javascript - 使用 ECMAScript 国际化 API 格式化日期和时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28545026/