我想用JS把一个 "日期对象 "变成一个 "YYYYMMDD "格式的字符串。 有没有比连接Date.getYear()
, Date.getMonth()
和Date.getDay()
更简单的方法?
我经常使用的修改过的一段代码。
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();
我不喜欢在原型上添加。 一个替代方案是
-- begin snippet: js hide: false console: truefalse -->
var rightNow = new Date();
var res = rightNow.toISOString().slice(0,10).replace(/-/g,"");
<!-- Next line is for code snippet output only -->
document.body.innerHTML += res;
<!--结束片段-->
你可以使用toISOString
函数。
var today = new Date();
today.toISOString().substring(0, 10);
它会给你一个"yy-mm-dd"。 格式。
var date = new Date();
var formattedDate = moment(date).format('YYYYMMDD');
[1]: http://momentjs.com/
除了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 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();
var hh = this.getHours() < 10 ? "0" + this.getHours() : this.getHours();
var min = this.getMinutes() < 10 ? "0" + this.getMinutes() : this.getMinutes();
return "".concat(yyyy).concat(mm).concat(dd).concat(hh).concat(min);
};
Date.prototype.yyyymmddhhmmss = 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();
var hh = this.getHours() < 10 ? "0" + this.getHours() : this.getHours();
var min = this.getMinutes() < 10 ? "0" + this.getMinutes() : this.getMinutes();
var ss = this.getSeconds() < 10 ? "0" + this.getSeconds() : this.getSeconds();
return "".concat(yyyy).concat(mm).concat(dd).concat(hh).concat(min).concat(ss);
};
var d = new Date();
d.yyyymmdd();
d.yyyymmddhhmm();
d.yyyymmddhhmmss();
按照RiZKiT的建议,再来点DRY的小提琴。
我不喜欢修改原生对象,我认为乘法比字符串填充公认的解决方案更清晰。
function yyyymmdd(dateIn) {
var yyyy = dateIn.getFullYear();
var mm = dateIn.getMonth()+1; // getMonth() is zero-based
var dd = dateIn.getDate();
return String(10000*yyyy + 100*mm + dd); // Leading zeros for mm and dd
}
var today = new Date();
console.log(yyyymmdd(today));
Fiddle:
在UTC中打印Date.toISOString()不会引起任何可能的日期跳转问题的纯JS(ES5)解决方案:。
var now = new Date();
var todayUTC = new Date(Date.UTC(now.getFullYear(), now.getMonth(), now.getDate()));
return todayUTC.toISOString().slice(0, 10).replace(/-/g, '');
这是对@weberste'对@Pierre Guilbert'的回答的回应。
<!--开始片段。 js hide.false --> -- begin snippet: js hide: false -->
// UTC/GMT 0
document.write('UTC/GMT 0: ' + (new Date()).toISOString().slice(0, 19).replace(/[^0-9]/g, "")); // 20150812013509
// Client local time
document.write('<br/>Local time: ' + (new Date(Date.now()-(new Date()).getTimezoneOffset() * 60000)).toISOString().slice(0, 19).replace(/[^0-9]/g, "")); // 20150812113509
<!--结束片段-->
另一种方法是使用toLocaleDateString`,并使用big-endian日期格式标准,如瑞典、立陶宛、匈牙利、韩国......。
date.toLocaleDateString('se')
要去掉定界符(-
),只需替换非数字即可。
<!--开始片段。 js hide: false console.true babel: true true babel.false -->-- begin snippet: js hide: false console: true false -->
console.log( new Date().toLocaleDateString('se').replace(/\D/g, '') );
<!--结束片段-->
这不会出现UTC日期格式的潜在错误。 UTC日期与当地时区的日期相比可能会有一天的偏差。
你可以简单地使用这一行代码来获取年份的日期。
var date = new Date().getFullYear() + "-" + (parseInt(new Date().getMonth()) + 1) + "-" + new Date().getDate();
这个帖子中最受欢迎的答案的简化版,有点https://stackoverflow.com/a/3067896/5437379 。
function toYYYYMMDD(d) {
var yyyy = d.getFullYear().toString();
var mm = (d.getMonth() + 101).toString().slice(-2);
var dd = (d.getDate() + 100).toString().slice(-2);
return yyyy + mm + dd;
}
似乎mootools提供了Date().format()
: https://mootools.net/more/docs/1.6.0/Types/Date
我不确定它是否值得包括在这个特定的任务中。
根据@o-o'的回答,这将根据格式字符串给你返回日期的字符串。 如果你需要的话,你可以很容易地添加一个2位数的年份regex来表示年份& 毫秒之类的,如果你需要的话,可以添加一个2位数的年份regex。
Date.prototype.getFromFormat = function(format) {
var yyyy = this.getFullYear().toString();
format = format.replace(/yyyy/g, yyyy)
var mm = (this.getMonth()+1).toString();
format = format.replace(/mm/g, (mm[1]?mm:"0"+mm[0]));
var dd = this.getDate().toString();
format = format.replace(/dd/g, (dd[1]?dd:"0"+dd[0]));
var hh = this.getHours().toString();
format = format.replace(/hh/g, (hh[1]?hh:"0"+hh[0]));
var ii = this.getMinutes().toString();
format = format.replace(/ii/g, (ii[1]?ii:"0"+ii[0]));
var ss = this.getSeconds().toString();
format = format.replace(/ss/g, (ss[1]?ss:"0"+ss[0]));
return format;
};
d = new Date();
var date = d.getFromFormat('yyyy-mm-dd hh:ii:ss');
alert(date);
我不知道这有多高效,但是,特别是perf明智,因为它使用了大量的regex.它可能会使用一些工作,我不掌握纯js。 它可能会使用一些工作,我不掌握纯js。
当我需要这样做的时候,我通常会使用下面的代码。
var date = new Date($.now());
var dateString = (date.getFullYear() + '-'
+ ('0' + (date.getMonth() + 1)).slice(-2)
+ '-' + ('0' + (date.getDate())).slice(-2));
console.log(dateString); //Will print "2015-09-18" when this comment was written
解释一下,.slice(-2)给了我们字符串的最后两个字符。
所以无论如何,我们都可以在日期或月份中添加"0" 到日期或月份,然后只要求最后两个字符,因为这两个字符总是我们想要的。
所以,如果MyDate.getMonth()返回9,就会是。
("0" + "9") // Giving us "09"
所以在上面加上.slice(-2)就得到了最后两个字符,也就是
("0" + "9").slice(-2)
"09"
但如果date.getMonth()返回的是10,就会。
("0" + "10") // Giving us "010"
所以加上.slice(-2)就得到最后两个字符,或者。
("0" + "10").slice(-2)
"10"