如何将Date对象格式化为字符串?
当前回答
注意(2022-10):toLocaleFormat已被弃用一段时间,并从Firefox版本58中删除。请参见LocaleFormat
我想你可以使用非标准的Date方法来LocaleFormat(formatString)
formatString:与C中strftime()函数期望的格式相同的格式字符串。
var today = new Date();
today.toLocaleFormat('%d-%b-%Y'); // 30-Dec-2011
参考文献:
到区域设置格式斯特夫蒂姆
其他回答
简短、广泛兼容的方法:
function formatDate(date) {
date.toISOString()
.replace(/^(\d+)-(\d+)-(\d+).*$/, // Only extract Y-M-D
function (a,y,m,d) {
return [
d, // Day
['Jan','Feb','Mar','Apr','May','Jun', // Month Names
'Jul','Ago','Sep','Oct','Nov','Dec']
[m-1], // Month
y // Year
].join('-') // Stitch together
})
}
或者,作为单行:
date.toISOString().replace(/^(\d+)-(\d+)-(\d+)T(\d+):(\d+):(\d+).(\d+)Z$/, function (a,y,m,d) {return [d,['Jan','Feb','Mar','Apr','May','Jun','Jul','Ago','Sep','Oct','Nov','Dic'][m-1],y].join('-')})
嗯,我想要的是将今天的日期转换为MySQL友好的日期字符串,如2012-06-23,并在我的一个查询中使用该字符串作为参数。我找到的简单解决方案是:
var today = new Date().toISOString().slice(0, 10);
请记住,上述解决方案没有考虑您的时区偏移。
您可以考虑改用此函数:
function toJSONLocal (date) {
var local = new Date(date);
local.setMinutes(date.getMinutes() - date.getTimezoneOffset());
return local.toJSON().slice(0, 10);
}
这将为您提供正确的日期,以防您在一天的开始/结束时执行此代码。
var date=新日期();函数到本地(日期){var local=新日期(日期);local.setMinutes(date.getMinutes()-date.getTimezoneOffset());return local.toJSON();}函数到JSONLocal(日期){var local=新日期(日期);local.setMinutes(date.getMinutes()-date.getTimezoneOffset());return local.toJSON().slice(0,10);}//查看您的devtools控制台console.log(date.toJSON());console.log(date.toISOString());console.log(toLocal(日期));console.log(toJSONLocal(日期));
日期.toISOString日期.toJSON字符串切片外部示例
var today = new Date();
var formattedToday = today.toLocaleDateString() + ' ' + today.toLocaleTimeString();
已缩小2.39KB。一个文件。https://github.com/rhroyston/clock-js2010年8月10日为:
var str = clock.month
str.charAt(0).toUpperCase() + str.slice(1,3); //gets you "Aug"
console.log(clock.day + '-' + str + '-' + clock.year); //gets you 10-Aug-2010
@Sébastien——可选的所有浏览器支持
new Date(parseInt(496407600)*1000).toLocaleDateString('de-DE', {
year: 'numeric',
month: '2-digit',
day: '2-digit'
}).replace(/\./g, '/');
文档:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleDateString
基于Date.toLocaleDateString的高阶标记模板文本示例:
const date = new Date(Date.UTC(2020, 4, 2, 3, 23, 16, 738));
const fmt = (dt, lc = "en-US") => (str, ...expr) =>
str.map((str, i) => str + (expr[i]?dt.toLocaleDateString(lc, expr[i]) :'')).join('')
console.log(fmt(date)`${{year: 'numeric'}}-${{month: '2-digit'}}-${{day: '2-digit'}}`);
// expected output: "2020-05-02"
推荐文章
- 如何将两个字符串相加,就好像它们是数字一样?
- 绑定多个事件到一个监听器(没有JQuery)?
- 在JavaScript中将JSON字符串解析为特定对象原型
- 将字符串“true”/“false”转换为布尔值
- 如何使用JavaScript代码获得浏览器宽度?
- event.preventDefault()函数在IE中无法工作
- indexOf()和search()的区别是什么?
- 错误:'types'只能在.ts文件中使用- Visual Studio Code使用@ts-check
- React-Native:应用程序未注册错误
- LoDash:从对象属性数组中获取值数组
- src和dist文件夹的作用是什么?
- jQuery UI对话框-缺少关闭图标
- SQL Developer只返回日期,而不是时间。我怎么解决这个问题?
- 如何使用AngularJS获取url参数
- 将RGB转换为白色的RGBA