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


当前回答

函数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>

其他回答

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

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;
}

DateFormatter.formatDate(新日期(2010,7,10),'DD-MMM-YYYY')

=>2010年8月10日

DateFormatter.formatDate(new Date(),'YYYY-MM-DD HH:MM:ss')

=>2017-11-22 19:52:37

DateFormatter.formatDate(新日期(2005,1,2,3,4,5),'D DD DDD DDD,M MM MMM MMMM,YY YYYY,h hh h hh,M MM,s ss,a a')

=>2002年2月2日星期三2005年2月5日,2003年3月3日,4月4日,5月5日上午

var日期格式设置工具={月份名称:[“一月”,“二月”,“三月”,“四月”,“五月”,“六月”,“七月”、“八月”、“九月”、“十月”、“十一月”、“十二月”],dayName:[“星期日”、“星期一”、“周二”、“周三”、“周四”、“周五”、“周六”],formatDate:函数(日期,格式){var self=this;format=self.getProperDigits(format,/d+/gi,date.getDate());format=self.getProperDigits(格式,/M+/g,date.getMonth()+1);format=format.replace(/y+/gi,函数(y){var len=y.length;var year=date.getFullYear();如果(长度==2)return(年份+“”).sslice(-2);否则如果(len==4)回归年;返回y;})format=self.getProperDigits(格式,/H+/g,date.getHours());format=self.getProperDigits(格式,/h+/g,self.getHours12(date.getHours()));format=self.getProperDigits(format,/m+/g,date.getMinutes());format=self.getProperDigits(format,/s+/gi,date.getSeconds());format=format.replace(/a/ig,函数(a){var amPm=self.getAmPm(date.getHours())如果(a==“a”)返回amPm.toUpperCase();返回amPm;})format=self.getFullOr3Letters(format,/d+/gi,self.dayNames,date.getDay())format=self.getFullOr3Letters(format,/M+/g,self.monthNames,date.getMonth())返回格式;},getProperDigits:函数(格式、正则表达式、值){return format.replace(正则表达式,函数(m){var长度=m.length;如果(长度==1)返回值;否则如果(长度==2)return(“0”+值).sslice(-2);返回m;})},getHours12:函数(小时){// https://stackoverflow.com/questions/10556879/changing-the-1-24-hour-to-1-12-hour-for-the-gethours-method返回(小时+24)%12||12;},getAmPm:函数(小时){// https://stackoverflow.com/questions/8888491/how-do-you-display-javascript-datetime-in-12-hour-am-pm-format回程时间>=12?'下午':'上午';},getFullOr3Letters:函数(格式,正则表达式,名称数组,值){return format.replace(正则表达式,函数){var len=s.length;如果(长度==3)return nameArray[value].substr(0,3);否则如果(len==4)return nameArray[value];返回s;})}}console.log(DateFormatter.formatDate(new Date(),'YYYY-MM-DD HH:MM:ss'));console.log(DateFormatter.formatDate(new Date(),'D DD DDD DDDD,M MM MMM MMMM,YY YYYY,h hh h hh,M MM,s ss,a a'));console.log(DateFormatter.formatDate(新日期(2005,1,2,3,4,5),'D DD DDD DDDD,M MM MMM MMMM,YY YYYY,h hh h hh,M MM,s ss,a a'));

格式描述取自Ionic Framework(它不支持Z、UTC时区偏移)

未彻底测试

函数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>

两个纯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(dDate,sMode){
    var today = dDate;
    var dd = today.getDate();
    var mm = today.getMonth()+1; //January is 0!
    var yyyy = today.getFullYear();
    if(dd<10) {
        dd = '0'+dd
    }
    if(mm<10) {
        mm = '0'+mm
    }
    if (sMode+""==""){
        sMode = "dd/mm/yyyy";
    }
    if (sMode == "yyyy-mm-dd"){
        return  yyyy + "-" + mm + "-" + dd + "";
    }
    if (sMode == "dd/mm/yyyy"){
        return  dd + "/" + mm + "/" + yyyy;
    }
}