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


当前回答

一行中请求的格式-没有库和Date方法,只有正则表达式:

var d = (new Date()).toString().replace(/\S+\s(\S+)\s(\d+)\s(\d+)\s.*/,'$2-$1-$3');
// date will be formatted as "14-Oct-2015" (pass any date object in place of 'new Date()')

在我的测试中,这在主要浏览器(Chrome、Safari、Firefox和IE)中可靠地工作。正如@RobG所指出的,Date.protype.toString()的输出依赖于实现,因此对于国际或非浏览器实现,只需测试输出,以确保它在JavaScript引擎中正常工作。您甚至可以添加一些代码来测试字符串输出,并在执行正则表达式替换之前确保其与预期匹配。

其他回答

new Date().toLocaleDateString()// "3/21/2018"

developer.mozilla.org上的更多文档

这可能有助于解决问题:

var d=新日期();var选项={day:'数字',月份:'long',年份:'数字'};console.log(d.toLocaleDateString('en-ZA',选项));

函数convert_month(i=0,option=“num”){//i=索引变量对象月=[{num:01,短:“Jan”,长:“Janer”},{num:02,短:“Feb”,长:“Februari”},{num:03,短:“Mar”,长:“March”},{num:04,短:“Apr”,长:“April”},{num:05,短:“May”,长:“May”},{num:06,短:“Jun”,长:“Juni”},{num:07,短:“Jul”,长:“July”},{num:08,短:“Aug”,长:“August”},{num:09,短:“Sep”,长:“Sept”},{num:10,短:“Oct”,长:“Octo”},{num:11,短:“Nov”,长:“十一月”},{num:12,短:“Dec”,长:“十二月”}];返回object_months[i][option];}var d=新日期();// https://stackoverflow.com/questions/1408289/how-can-i-do-string-interpolation-in-javascriptvar num=`${d.getDate()}-${convert_month(d.getMonth())}--${d.getFullYear()}';var short=`${d.getDate()}-${convert_month(d.getMonth(),“short”)}-${d.getFullYear()}`;var long=`${d.getDate()}-${convert_month(d.getMonth(),“long”)}-${d.getFullYear()}`;document.querySelector(“#num”).innerHTML=num;document.querySelector(“#short”).innerHTML=短;document.querySelector(“#long”).innerHTML=long;<p>数字:<span id=“num”></span>(默认值)</p><p>短:<span id=“Short”></span></p><p>长:<span id=“Long”></span></p>

简短、广泛兼容的方法:

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('-')})

你应该看看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>