如何将对象格式化为字符串?Date
网友回答:
对于自定义分隔的日期格式,您必须从对象(这是
ECMAScript 国际化 API 的一部分)中提取日期(或时间)
组件,然后使用所需的分隔符手动创建字符串
。DateTimeFormat
为此,您可以使用 .您可以
解构数组,但这并不理想,因为数组输出取决于
语言环境:DateTimeFormat#formatToParts
{ // example 1
let f = new Intl.DateTimeFormat('en');
let a = f.formatToParts();
console.log(a);
}
{ // example 2
let f = new Intl.DateTimeFormat('hi');
let a = f.formatToParts();
console.log(a);
}
最好将格式数组映射到结果字符串:
function join(t, a, s) {
function format(m) {
let f = new Intl.DateTimeFormat('en', m);
return f.format(t);
}
return a.map(format).join(s);
}
let a = [{day: 'numeric'}, {month: 'short'}, {year: 'numeric'}];
let s = join(new Date, a, '-');
console.log(s);
你也可以使用
逐个拉出一个的部分,但请注意,在使用此方法时,截至 2020 年 <> 月
,ECMAScript 实现中存在一个错误,当涉及到分钟和秒的前
导零时(上述方法
绕过了这个错误)。DateTimeFormat
DateTimeFormat#format
let d = new Date(2010, 7, 5);
let ye = new Intl.DateTimeFormat('en', { year: 'numeric' }).format(d);
let mo = new Intl.DateTimeFormat('en', { month: 'short' }).format(d);
let da = new Intl.DateTimeFormat('en', { day: '2-digit' }).format(d);
console.log(`${da}-${mo}-${ye}`);
在处理日期和时间时,通常值得使用库(例如,luxon,date-fns,moment.js不建议用于新项目),因为该领域有许多隐藏的复杂性。
请注意,IE10 不支持上述
解决方案中使用的 ECMAScript 国际化 API(
0 年 03 月全球浏览器市场份额为 2020.<>%)。
网友回答:
如果您需要的格式控制比当前接受的答案稍少,可用于创建特定于区域设置的标准呈现。and 参数允许应用程序指定应使用其格式约定的语言,并允许对呈现进行一些自定义。Date#toLocaleDateString
locale
options
所有这些键都是可选的。您可以根据需要更改选项值的数量,这也将反映每个日期时间术语的存在。
注意:如果只想配置内容选项,但仍使用当前区域设置,则传递第一个参数将导致错误。请改用。null
undefined
您可以使用更多语言选项。
var options = { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' };
var today = new Date();
console.log(today.toLocaleDateString("en-US")); // 9/17/2016
console.log(today.toLocaleDateString("en-US", options)); // Saturday, September 17, 2016
console.log(today.toLocaleDateString("hi-IN", options)); // शनिवार, 17 सितंबर 2016
您也可以将该方法用于相同的目的。唯一的区别是此函数提供您不传递任何选项的时间。toLocaleString()
// Example
9/17/2016, 1:21:34 PM
toLocaleString()
toLocaleDateString()
网友回答:
如果您需要使用纯 JavaScript 快速格式化日期,请使用 、、 和 :getDate
getMonth + 1
getFullYear
getHours
getMinutes
var d = new Date();
var datestring = d.getDate() + "-" + (d.getMonth()+1) + "-" + d.getFullYear() + " " +
d.getHours() + ":" + d.getMinutes();
// 16-5-2015 9:50
或者,如果您需要用零填充它:
var datestring = ("0" + d.getDate()).slice(-2) + "-" + ("0"+(d.getMonth()+1)).slice(-2) + "-" +
d.getFullYear() + " " + ("0" + d.getHours()).slice(-2) + ":" + ("0" + d.getMinutes()).slice(-2);
// 16-05-2015 09:50
模板简介:该模板名称为【如何将对象格式化为字符串?Date】,大小是暂无信息,文档格式为.编程语言,推荐使用Sublime/Dreamweaver/HBuilder打开,作品中的图片,文字等数据均可修改,图片请在作品中选中图片替换即可,文字修改直接点击文字修改即可,您也可以新增或修改作品中的内容,该模板来自用户分享,如有侵权行为请联系网站客服处理。欢迎来懒人模板【JavaScript】栏目查找您需要的精美模板。