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


当前回答

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

developer.mozilla.org上的更多文档

其他回答

不使用任何外部库的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)

一个简单的函数,可以返回日期、日期+时间或仅返回时间:

var myDate = dateFormatter("2019-01-24 11:33:24", "date-time");
// >> RETURNS "January 24, 2019 11:33:24"

var myDate2 = dateFormatter("2019-01-24 11:33:24", "date");
// >> RETURNS "January 24, 2019"

var myDate3 = dateFormatter("2019-01-24 11:33:24", "time");
// >> RETURNS "11:33:24"


function dateFormatter(strDate, format){
    var theDate = new Date(strDate);
    if (format=="time")
       return getTimeFromDate(theDate);
    else{
       var dateOptions = {year:'numeric', month:'long', day:'numeric'};
       var formattedDate = theDate.toLocaleDateString("en-US", + dateOptions);
       if (format=="date")
           return formattedDate;
       return formattedDate + " " + getTimeFromDate(theDate);
    }
}

function getTimeFromDate(theDate){
    var sec = theDate.getSeconds();
    if (sec<10)
        sec = "0" + sec;
    var min = theDate.getMinutes();
    if (min<10)
        min = "0" + min;
    return theDate.getHours() + ':'+ min + ':' + sec;
}

试试看:

函数init(){var d=新日期();var day=d.getDate();var x=d.toDateString().substr(4,3);var year=d.getFullYear();document.querySelector(“#mydate”).innerHTML=day+'-'+x+'-'+年;}window.onload=init;<div id=“mydate”></div>

两个纯JavaScript单行程序

在这个答案中,我发展了JD Smith的想法。我能够缩短JD-Smith正则表达式。

let format=d=>d.toString().replace(/\w+(\w+)(\d+)(\d+).*/,'$2-$1-$3');console.log(格式(Date()));

Dave的也是基于JD Smith的想法,但他避免了正则表达式,并给出了一个非常好的解决方案——我稍微缩短了他的解决方案(通过更改拆分参数),并在包装器中使其不透明。

let format=(d,a=d.toString().split``)=>a[2]+“-”+a[1]+“-“+a[3];console.log(格式(Date()));

简短、广泛兼容的方法:

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