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


当前回答

以下代码将允许您将日期格式设置为DD-MM-YYYY(2017年12月27日)或DD-MM-YYYY(2017年10月26日):

/** Pad number to fit into nearest power of 10 */
function padNumber(number, prependChar, count) {
  var out = '' + number; var i;
  if (number < Math.pow(10, count))
    while (out.length < ('' + Math.pow(10, count)).length) out = prependChar + out;
  
  return out;
}

/* Format the date to 'DD-MM-YYYY' or 'DD MMM YYYY' */
function dateToDMY(date, useNumbersOnly) {
  var months = [
    'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 
    'Nov', 'Dec'
  ];

  return '' + padNumber(date.getDate(), '0', 1) + 
   (useNumbersOnly? '-' + padNumber(date.getMonth() + 1, '0', 1) + '-' : ' ' + months[date.getMonth()] + ' ')
    + date.getFullYear();
}

更改date.getFullYear()和padNumber(date.getDate(),“0”,1)的顺序,以生成dateToYMD()函数。

有关详细信息,请参见repl.it示例。

其他回答

设置日期格式的其他方式:

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

字符串转换


// date 
const dateConvert = {
  dasher: dt => {
    let m = (dt.getMonth() + 1) === 13 ? 1 : (dt.getMonth() + 1);
    m = m < 10 ? `0${m}` : m.toString();
    let d = dt.getDate();
    d = d < 10 ? `0${d}` : d.toString();
    return `${dt.getFullYear()}-${m}-${d}`;
  }, 
  slasher: dt => {
    return dateConvert.slash(dateConvert.dasher(dt));
  }, 
  dash: str => {
    // 03/11/2022 -> 2022-03-11
    let [d, m, y] = str.split('/');
    return `${y}-${m}-${d}`;
  }, 
  slash: str => {
    // 2022-03-11 -> 03/11/2022
    let [y, m, d] = str.split('-');
    return `${d}/${m}/${y}`
  }
}

// console.log(dateConvert.dasher(new Date('01/31/2001')));

如果您需要使用普通JavaScript快速格式化日期,请使用getDate、getMonth+1、getFullYear、getHours和getMinutes:

var d = new Date();

var datestring = d.getDate()  + "-" + (d.getMonth()+1) + "-" + d.getFullYear() + " " +
d.getHours() + ":" + d.getMinutes();

// 16-5-2015 9:50

或者,如果需要用零填充:

var datestring = ("0" + d.getDate()).slice(-2) + "-" + ("0"+(d.getMonth()+1)).slice(-2) + "-" +
    d.getFullYear() + " " + ("0" + d.getHours()).slice(-2) + ":" + ("0" + d.getMinutes()).slice(-2);

// 16-05-2015 09:50
var today = new Date();
var formattedToday = today.toLocaleDateString() + ' ' + today.toLocaleTimeString();

简短、广泛兼容的方法:

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