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


当前回答

你应该看看DayJs。它是momentJs的翻版,但模块化架构更轻。

快速2kB替代Moment.js,具有相同的现代API

Day.js是一个极简的JavaScript库,它使用Moment.js兼容的API为现代浏览器解析、验证、操作和显示日期和时间。如果您使用Moment.js,您已经知道如何使用Day.js。

var date=date.now();const formatedDate=dayjs(日期).format(“YYYY-MM-DD”)console.log(formatedDate);<script src=“https://cdnjs.cloudflare.com/ajax/libs/dayjs/1.8.16/dayjs.min.js“crossoorigin=”匿名“></script>

其他回答

Sugar.js对Date对象有很好的扩展,包括Date.format方法。

文档中的示例:

Date.create().format('{Weekday} {Month} {dd}, {yyyy}');

Date.create().format('{12hr}:{mm}{tt}')

将jQuery UI插件添加到页面:

function DateFormate(dateFormate, datetime) {
    return $.datepicker.formatDate(dateFormate, datetime);
};

不使用任何外部库的JavaScript解决方案:

var now = new Date()
months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
var formattedDate = now.getDate() + "-" + months[now.getMonth()] + "-" + now.getFullYear()
alert(formattedDate)

我们有很多解决方案,但我认为最好的是Moment.js。所以我个人建议将Moment.jss用于日期和时间操作。

console.log(moment().format('DD-MMM-YYYY'));<script src=“//cdnjs.cloudflare.com/ajax/libs/ment.js/2.14.1/moment.min.js”></script>

为了将日期格式化为例如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('-')