通常,如果我想获取日期,我可以执行以下操作:
var d = new Date();
console.log(d);
问题在于,当我运行该代码时,它会返回:
Mon Aug 24 2015 4:20:00 GMT-0800 (Pacific Standard Time)
我如何使Date()方法返回一个"MM-DD-YYYY"格式的值,以便返回以下结果:
8/24/2015
或者,也可以是 MM-DD-YYYY H:M
8/24/2016 4:20
通常,如果我想获取日期,我可以执行以下操作:
var d = new Date();
console.log(d);
问题在于,当我运行该代码时,它会返回:
Mon Aug 24 2015 4:20:00 GMT-0800 (Pacific Standard Time)
我如何使Date()方法返回一个"MM-DD-YYYY"格式的值,以便返回以下结果:
8/24/2015
或者,也可以是 MM-DD-YYYY H:M
8/24/2016 4:20
function formatDateYYYYMMDDHHMMSS(date){
// YYYY-MM-DD HH:MM:SS
const datePart = date.toISOString().split("T")[0]
const timePart = date.toLocaleString('en-US', {hour12: false}).split(",")[1]
return datePart + timePart
}
作为原型:
Date.prototype.toSortString = function(){
const date = new Date(this.valueOf());
return date.toISOString().split("T")[0] +
date.toLocaleString('en-US', {hour12: false}).split(",")[1]
}
toISOString
会从本地时间转换为UTC时间。 - Auspexfunction (date) {
return new Date(+date - date.getTimezoneOffset() * 60 * 1000).toISOString().split(/[TZ]/).slice(0, 2).join(' ');
}
+date
从日期中获取毫秒。
参考:Date.prototype.getTimezoneOffset 玩得开心 :)
function returnYYYYMMDD(numFromToday = 0){
let d = new Date();
d.setDate(d.getDate() + numFromToday);
const month = d.getMonth() < 9 ? '0' + (d.getMonth() + 1) : d.getMonth() + 1;
const day = d.getDate() < 10 ? '0' + d.getDate() : d.getDate();
return `${d.getFullYear()}-${month}-${day}`;
}
console.log(returnYYYYMMDD(-1)); // returns yesterday
console.log(returnYYYYMMDD()); // returns today
console.log(returnYYYYMMDD(1)); // returns tomorrow
可以轻松地修改以传递日期,但在这里您传递一个数字,它将从今天开始返回那么多天。
(new Date().toLocaleString("en-CA",
{ timeZone: 'America/Los_Angeles', hourCycle: 'h24',
year: 'numeric', month: '2-digit', day: '2-digit',
hour: '2-digit', minute: '2-digit', second: '2-digit'})).replace(/\D+/g, '-')
// Output: '2023-10-03-09-16-12'
const padTo2Digits = num => {
return num.toString().padStart(2, '0')
}
const formatDate = date => {
return [
date.getFullYear(),
padTo2Digits(date.getMonth() + 1),
padTo2Digits(date.getDate())
].join('-')
}
let value = formatDate(new Date())
document.getElementById('dayFormatUS').innerHTML = value
const transformDate = date => {
const convert = date.split('-').reverse()
return convert.join('/')
}
document.getElementById('dayFormatBR').innerHTML = transformDate(value)
<div>
Format US -
<span id='dayFormatUS'></span>
</div>
<div>
Format BR -
<span id='dayFormatBR'></span>
</div>
d.toISOString().split('T')[0]
的意思是将日期对象d转换为ISO格式的字符串,并将其按照'T'字符拆分为两部分,然后返回第一部分(即只包含日期信息的部分)。 - Paul S.d.toLocaleDateString()
怎么样?这将给你与你第一个示例完全相同的结果。 - cezar