当我们在date对象上调用getMonth()和getDate()时,我们将得到一个个位数。 例如:
对于一月份,它显示为1,但我需要将其显示为01。怎么做呢?
当我们在date对象上调用getMonth()和getDate()时,我们将得到一个个位数。 例如:
对于一月份,它显示为1,但我需要将其显示为01。怎么做呢?
当前回答
const today = new Date().toISOString()
const fullDate = today.split('T')[0];
console.log(fullDate) //prints YYYY-MM-DD
其他回答
new Date().getMonth()方法以数字形式返回月份(0-11)
用这个函数你可以很容易地得到正确的月份数。
function monthFormatted() {
var date = new Date(),
month = date.getMonth();
return month+1 < 10 ? ("0" + month) : month;
}
$("body").delegate("select[name='package_title']", "change", function() {
var price = $(this).find(':selected').attr('data-price');
var dadaday = $(this).find(':selected').attr('data-days');
var today = new Date();
var endDate = new Date();
endDate.setDate(today.getDate()+parseInt(dadaday));
var day = ("0" + endDate.getDate()).slice(-2)
var month = ("0" + (endDate.getMonth() + 1)).slice(-2)
var year = endDate.getFullYear();
var someFormattedDate = year+'-'+month+'-'+day;
$('#price_id').val(price);
$('#date_id').val(someFormattedDate);
});
如果你检查的是小于10的,你不需要为它创建一个新函数。只需将变量赋值到括号中,并返回一个三元操作符。
(m = new Date().getMonth() + 1) < 10 ? `0${m}` : `${m}`
来自MDN的建议:
function date_locale(thisDate, locale) {
if (locale == undefined)
locale = 'fr-FR';
// set your default country above (yes, I'm french !)
// then the default format is "dd/mm/YYY"
if (thisDate == undefined) {
var d = new Date();
} else {
var d = new Date(thisDate);
}
return d.toLocaleDateString(locale);
}
var thisDate = date_locale();
var dayN = thisDate.slice(0, 2);
var monthN = thisDate.slice(3, 5);
console.log(dayN);
console.log(monthN);
http://jsfiddle.net/v4qcf5x6/
如果你能给我点时间的话我想问的是
YYYYMMDD
为了今天,和大家相处:
const dateDocumentID = new Date()
.toISOString()
.substr(0, 10)
.replace(/-/g, '');