我试图使用JS将日期对象转换为YYYYMMDD格式的字符串。有没有比连接Date.getYear(), Date.getMonth()和Date.getDay()更简单的方法?
当前回答
我不喜欢修改本机对象,而且我认为乘法比填充接受的解决方案的字符串更清楚。
函数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/
其他回答
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();
要获得本地日期,YYYYMMDD格式,我使用:
var todayDate = (new Date()).toLocaleString('en-GB').slice(0,10).split("\/").reverse().join("");
yyyymmdd=x=>(f=x=>(x<10&&'0')+x,x.getFullYear()+f(x.getMonth()+1)+f(x.getDate())); 警报(年年月日(新日期));
我经常使用的一段修改代码:
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();
我写了一个简单的函数,它可以将Date对象转换为具有日期号、月份号(带零填充)和年份号的可定制顺序的String。您可以将它与您喜欢的任何分隔符一起使用,或者将此参数保留为空以在输出中不显示分隔符。请看一看。
function dateToString(date, $1, $2, $3, separator='') { const dateObj = { date: String(date.getDate()).padStart(2, '0'), month: String(date.getMonth() + 1).padStart(2, '0'), year: date.getFullYear() }; return dateObj[$1] + separator + dateObj[$2] + separator + dateObj[$3]; } const date = new Date(); const dateString1 = dateToString(date, 'year', 'month', 'date'); console.log(dateString1); // Manipulate arguments order to get output you want const dateString2 = dateToString(date, 'date', 'month', 'year', '-'); console.log(dateString2);