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


当前回答

这是一行代码,您可以使用它来创建今天日期的YYYY-MM-DD字符串。

var d = new Date().toISOString().slice(0,10);

其他回答

我试图写一个简单的库操作JavaScript日期对象。你可以试试这个。

var dateString = timeSolver.getString(date, "YYYYMMDD")

Libarary: https://github.com/sean1093/timeSolver

除了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>

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

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'));

Dateformat是一个非常常用的包。

使用方法:

从NPM下载并安装dateformat。在你的模块中需要它:

以格式

然后格式化你的东西:

const myYYYYmmddDate = dateformat(new Date(), 'yyyy-mm-dd');

原生Javascript:

new Date().toLocaleString('zu-ZA').slice(0,10).replace(/-/g,'');