overus Asked:2022-05-20 19:36:18 +0000 UTC2022-05-20 19:36:18 +0000 UTC 2022-05-20 19:36:18 +0000 UTC 如何以 yyyyMMdd 格式获取日期? 772 如何获取今天的数字 12/20/2021(或任何其他这种格式),以便将其转换为这种形式:20211220? javascript 2 个回答 Voted Best Answer Aleksandr Belous 2022-05-20T19:44:29Z2022-05-20T19:44:29Z const date = Date.now(); // timestamp какого-либо дня const anotherDate = new Date('2021-01-01'); // доп форматирование значений с одним числом const format = (date) => date < 10 ? `0${date}` : date.toString(); const getDateString = (timestamp) => { const date = new Date(timestamp); const day = date.getDate(); const month = date.getMonth() + 1; const year = date.getFullYear(); return `${year}${format(month)}${format(day)}`; }; console.log(getDateString(date)); // 20211220 console.log(getDateString(anotherDate)); // 20210101 entithat 2022-05-20T20:07:07Z2022-05-20T20:07:07Z 更简洁的解决方案: function fd(date) { return ['year', 'month', 'day'].map(e => new Intl.DateTimeFormat('en', { [e]: 'numeric', }).format(date).padStart(2, '0')).join``; } console.log(fd(new Date)); console.log(fd(new Date(2021, 1, 1)));
更简洁的解决方案: