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


当前回答

这里有一个简洁的小函数,易于阅读,并避免了局部变量,这在JavaScript中可能是时间消耗。我不使用原型来修改标准模块,因为它会污染名称空间,并可能导致代码不能执行您认为应该执行的操作。

main函数有一个愚蠢的名字,但它传达了思想。

function dateToYYYYMMDDhhmmss(date) {
    function pad(num) {
        num = num + '';
        return num.length < 2 ? '0' + num : num;
    }
    return date.getFullYear() + '/' +
        pad(date.getMonth() + 1) + '/' +
        pad(date.getDate()) + ' ' +
        pad(date.getHours()) + ':' +
        pad(date.getMinutes()) + ':' +
        pad(date.getSeconds());
}

其他回答

我不喜欢增加原型。另一种选择是:

var rightNow = new Date(); var res = rightNow.toISOString().slice(0,10).replace(/-/g,""); <!——下一行仅用于代码段输出——> document.body.innerHTML += res;

当然,您可以为日期字符串表示形式的每种变化构建特定的函数。如果您考虑国际日期格式,那么您会得到几十个名称荒谬且难以区分的特定函数。

没有匹配所有格式的合理函数,但有一个合理的函数组合:

const pipe2 = f => g => x => g(f(x)); const pipe3 = f => g => h => x => h(g(f(x))); const invoke = (method, ...args) => o => o[method] (...args); const padl = (c, n) => s => c.repeat(n) .concat(s) .slice(-n); const inc = n => n + 1; // generic format date function const formatDate = stor => (...args) => date => args.map(f => f(date)) .join(stor); // MAIN const toYYYYMMDD = formatDate("") ( invoke("getFullYear"), pipe3(invoke("getMonth")) (inc) (padl("0", 2)), pipe2(invoke("getDate")) (padl("0", 2))); console.log(toYYYYMMDD(new Date()));

是的,这是一大堆代码。但是,您可以通过简单地更改传递给高阶函数formatDate的函数参数来逐字地表示每个字符串日期表示。一切都是显式的和声明性的,也就是说,你几乎可以读到发生了什么。

我经常使用的一段修改代码:

Date.prototype.yyyymmdd = function() {
  var mm = this.getMonth() + 1; // getMonth() is zero-based
  var dd = this.getDate();

  return [this.getFullYear(),
          (mm>9 ? '' : '0') + mm,
          (dd>9 ? '' : '0') + dd
         ].join('');
};

var date = new Date();
date.yyyymmdd();

一个衬线(2022),带正确的时区偏移

var dateDisplay = new Date(Date.now() - (new Date().getTimezoneOffset() * 1000 * 60)).toJSON().slice(0, 10).replaceAll("-", "");

// YearMonthDay var dateDisplay = new Date(Date.now() - (new Date().getTimezoneOffset() * 1000 * 60)).toJSON().slice(0, 10).replaceAll("-", ""); console.log("YearMonthDay"); console.log(dateDisplay); // Year-Month-Day var dateDisplay = new Date(Date.now() - (new Date().getTimezoneOffset() * 1000 * 60)).toJSON().slice(0, 10); console.log("Year-Month-Day"); console.log(dateDisplay); // Year-Month-Day Hour:Minute:Second var dateDisplay = new Date(Date.now() - (new Date().getTimezoneOffset() * 1000 * 60)).toJSON().slice(0, 19).replace("T", " "); console.log("Year-Month-Day Hour:Minute:Second"); console.log(dateDisplay); // Year-Month-Day Hour-Minute-Second var dateDisplay = new Date(Date.now() - (new Date().getTimezoneOffset() * 1000 * 60)).toJSON().slice(0, 19).replace("T", " ").replaceAll(":", "-"); console.log("Year-Month-Day Hour-Minute-Second"); console.log(dateDisplay); // ISO-8601 standard: YYYY-MM-DDTHH:mm:ss.sssZ var dateDisplay = new Date(Date.now() - (new Date().getTimezoneOffset() * 1000 * 60)).toJSON(); console.log("ISO-8601 standard: YYYY-MM-DDTHH:mm:ss.sssZ"); console.log(dateDisplay);

Try this:

函数showdate () {

var a = new Date();
var b = a.getFullYear();
var c = a.getMonth();
(++c < 10)? c = "0" + c : c;
var d = a.getDate();
(d < 10)? d = "0" + d : d;
var final = b + "-" + c + "-" + d; 

return final;


} 

document.getElementById("todays_date").innerHTML = showdate();