如何将Date对象格式化为字符串?


当前回答

对于自定义分隔日期格式,必须拉出日期(或时间)DateTimeFormat对象(它是ECMAScript国际化API),然后手动创建字符串使用所需的分隔符。

为此,可以使用DateTimeFormat#formatToParts。你可以销毁数组,但这并不理想,因为数组输出取决于区域设置:

{//示例1设f=新Intl.DateTimeFormat('en');让a=f.formatToParts();控制台日志(a);}{//示例2设f=新Intl.DateTimeFormat('hi');让a=f.formatToParts();控制台日志(a);}

最好将格式数组映射到结果字符串:

函数连接(t,a,s){函数格式(m){设f=新Intl.DateTimeFormat('en',m);返回f.format(t);}返回.map(格式).join(s);}让a=〔{日:‘数字’},{月:‘短’}、{年:‘数字”}〕;let s=join(新日期,a,'-');console.log;

还可以使用DateTimeFormat#格式,但请注意,使用此方法时,截至3月2020年,当涉及到分钟和秒的前导零(该方法避免了此错误以上)。

设d=新日期(2010,7,5);let ye=新Intl.DateTimeFormat('en',{year:'numeric'}).format(d);let mo=新Intl.DateTimeFormat('en',{month:'short'}).format(d);let da=新Intl.DateTimeFormat('en',{day:'2-位'}).format(d);console.log(`${da}--${mo}-${ye}');

在处理日期和时间时,通常值得使用库(例如,luxon、date fns、moment.js不建议用于新项目),因为该领域有许多隐藏的复杂性。

注意,上述解决方案中使用的ECMAScript国际化APIIE10不支持(2月全球浏览器市场份额为0.03%)2020).

其他回答

为了将日期格式化为例如2010年8月10日,您可能需要使用.toDateString()和ES6数组析构函数。

const formattedDate = new Date().toDateString()
// The above yields e.g. 'Mon Jan 06 2020'

const [, month, day, year] = formattedDate.split(' ')

const ddMmmYyyy = `${day}-${month}-${year}`
// or
const ddMmmYyyy = [day, month, year].join('-')

普通JavaScript是小型一次性应用程序的最佳选择。

另一方面,如果你需要更多约会内容,MomentJS是一个很好的解决方案。

例如:

moment().format('YYYY-MM-DD HH:m:s');     // now() -> 2015-03-24 14:32:20
moment("20111031", "YYYYMMDD").fromNow(); // 3 years ago
moment("20120620", "YYYYMMDD").fromNow(); // 3 years ago
moment().startOf('day').fromNow();        // 11 hours ago
moment().endOf('day').fromNow();          // in 13 hours

这可以帮助:

export const formatDateToString = date => {
    if (!date) {
        return date;
    }
    try {
        return format(parse(date, 'yyyy-MM-dd', new Date()), 'dd/MM/yyyy');
    } catch (error) {
        return 'invalid date';
    }
};

在我的情况下,我已将日期表“2022年7月1日”格式化为“2022-07-01”

常量格式日期=日期=>{const d=新日期(日期)let month=(d.getMonth()+1).toString()let day=d.getDate().toString()const year=d.getFullYear()如果(月长度<2){月=“0”+月}如果(日长度<2){天=“0”+天}return[年,月,日]。join('-')}console.log(格式日期('01/07/2022'))

这是修改为3个字符月和2位数年的主要答案:

函数formatDate(日期){var monthNames=[“一月”,“二月”,“三月”,“四月”,“五月”,“六月”,“七月”,“八月”,“九月”,“十月”,“十一月”,“十二月”];var day=date.getDate(),monthIndex=date.getMonth(),year=date.getFullYear().toString().substr(-2);return day+''+monthNames[monthIndex]+''+年;}document.write(formatDate(newDate()));