我试图使用JS将日期对象转换为YYYYMMDD格式的字符串。有没有比连接Date.getYear(), Date.getMonth()和Date.getDay()更简单的方法?


当前回答

下面是一种更通用的方法,它允许日期和时间组件,并且可以作为数字或字符串进行相同的排序。

根据“Date ISO format”中的数字顺序,转换为本地时区,去掉非数字。例如:

// monkey patch version
Date.prototype.IsoNum = function (n) {
    var tzoffset = this.getTimezoneOffset() * 60000; //offset in milliseconds
    var localISOTime = (new Date(this - tzoffset)).toISOString().slice(0,-1);
    return localISOTime.replace(/[-T:\.Z]/g, '').substring(0,n || 20); // YYYYMMDD
}

使用

var d = new Date();
// Tue Jul 28 2015 15:02:53 GMT+0200 (W. Europe Daylight Time)
console.log(d.IsoNum(8));  // "20150728"
console.log(d.IsoNum(12)); // "201507281502"
console.log(d.IsoNum());   // "20150728150253272"

其他回答

似乎mootools提供了Date().format(): https://mootools.net/more/docs/1.6.0/Types/Date

但我不确定是否值得只针对这个特定的任务。

我不喜欢修改本机对象,而且我认为乘法比填充接受的解决方案的字符串更清楚。

函数yyyymmdd(dateIn) { var yyyy = dateIn.getFullYear(); var mm = dateIn.getMonth() + 1;// getMonth()是从零开始的 var dd = dateIn.getDate(); 返回String(10000 * yyyy + 100 * mm + dd);// mm和dd的前导零 } var today = new Date(); console.log(名称(今天));

小提琴:http://jsfiddle.net/gbdarren/Ew7Y4/

这段代码修复了Pierre Guilbert的答案:

(10000年后依然有效)

YYYYMMDD=new Date().toISOString().slice(0,new Date().toISOString().indexOf("T")).replace(/-/g,"")

您可以创建自己的函数,如下所示

function toString(o, regex) {
    try {
        if (!o) return '';
        if (typeof o.getMonth === 'function' && !!regex) {
            let splitChar = regex.indexOf('/') > -1 ? '/' : regex.indexOf('-') > -1 ? '-' : regex.indexOf('.') > -1 ? '.' : '';
            let dateSeparate = regex.split(splitChar);
            let result = '';
            for (let item of dateSeparate) {
                let val = '';
                switch (item) {
                    case 'd':
                        val = o.getDate();
                        break;
                    case 'dd':
                        val = this.date2Char(o.getDate());
                        break;
                    case 'M':
                        val = o.getMonth() + 1;
                        break;
                    case 'MM':
                        val = this.date2Char(o.getMonth() + 1);
                        break;
                    case 'yyyy':
                        val = o.getFullYear();
                        break;
                    case 'yy':
                        val = this.date2Char(o.getFullYear());
                        break;
                    default:
                        break;
                }
                result += val + splitChar;
            }
            return result.substring(0, result.length - 1);
        } else {
            return o.toString();
        }
    } catch(ex) { return ''; }
}

function concatDateToString(args) {
    if (!args.length) return '';
    let result = '';
    for (let i = 1; i < args.length; i++) {
        result += args[i] + args[0];
    }
    return result.substring(0, result.length - 1);
}

function date2Char(d){
    return this.rightString('0' + d);
}

function rightString(o) {
    return o.substr(o.length - 2);
}

使用:

var a = new Date();
console.log('dd/MM/yyyy: ' + toString(a, 'dd/MM/yyyy'));
console.log('MM/dd/yyyy: ' + toString(a, 'MM/dd/yyyy'));
console.log('dd/MM/yy: ' + toString(a, 'dd/MM/yy'));
console.log('MM/dd/yy: ' + toString(a, 'MM/dd/yy'));

除了o-o的答案之外,我还建议将逻辑操作与返回值分离,并将它们作为三元放入变量中。

另外,使用concat()来确保变量的安全连接

Date.prototype.yyyymmdd = function() { var yyyy = this.getFullYear(); var mm = this.getMonth() < 9 ? "0" + (this.getMonth() + 1) : (this.getMonth() + 1); // getMonth() is zero-based var dd = this.getDate() < 10 ? "0" + this.getDate() : this.getDate(); return "".concat(yyyy).concat(mm).concat(dd); }; Date.prototype.yyyymmddhhmm = function() { var yyyymmdd = this.yyyymmdd(); var hh = this.getHours() < 10 ? "0" + this.getHours() : this.getHours(); var min = this.getMinutes() < 10 ? "0" + this.getMinutes() : this.getMinutes(); return "".concat(yyyymmdd).concat(hh).concat(min); }; Date.prototype.yyyymmddhhmmss = function() { var yyyymmddhhmm = this.yyyymmddhhmm(); var ss = this.getSeconds() < 10 ? "0" + this.getSeconds() : this.getSeconds(); return "".concat(yyyymmddhhmm).concat(ss); }; var d = new Date(); document.getElementById("a").innerHTML = d.yyyymmdd(); document.getElementById("b").innerHTML = d.yyyymmddhhmm(); document.getElementById("c").innerHTML = d.yyyymmddhhmmss(); <div> yyyymmdd: <span id="a"></span> </div> <div> yyyymmddhhmm: <span id="b"></span> </div> <div> yyyymmddhhmmss: <span id="c"></span> </div>