【发布时间】:2020-11-15 04:07:18
【问题描述】:
请任何人分享从这种格式日期(2020,7,24,11,0)中减去月份的代码。例如,当前日期和时间是 (2020,7,24, 11,0),我得到 (2020,6,24, 11,0)。有人可以帮我怎么办吗?
【问题讨论】:
标签: javascript angular date date-format angular-moment
请任何人分享从这种格式日期(2020,7,24,11,0)中减去月份的代码。例如,当前日期和时间是 (2020,7,24, 11,0),我得到 (2020,6,24, 11,0)。有人可以帮我怎么办吗?
【问题讨论】:
标签: javascript angular date date-format angular-moment
如果你有对象日期,那很简单:
const d = new Date(2020,7,24, 11,0);
// Remember in Date months starts from 0
console.log(d);
// Substract 1 month
d.setMonth(d.getMonth() - 1);
// Log
console.log(d);
或者如果需要,可以手动解析
// Set raw
const rawDate = '2020,7,24, 11,0';
console.log(rawDate);
// Convert your date
const [year, month, day, hour, minute] = rawDate.split(',');
// Set date
var d = new Date();
d.setFullYear(year);
d.setMonth(month-1); // Month starts from 0
d.setDate(day);
d.setHours(hour);
d.setMinutes(minute);
console.log(d);
// Substract month
d.setMonth(d.getMonth() - 1);
// Log
console.log(d);
// If you need to convert back to your format
const rawDateModified = `${d.getFullYear()},${d.getMonth()+1},${d.getDate()}, ${d.getHours()},${d.getMinutes()}`;
console.log(rawDateModified);
更新了答案以显示如何将字符串传递给 Date 对象
// You get ds Date param as string
let ds = "2020,2,28,3,44";
// To pass it in Date object, you must
// convert it to array by splitting string
ds = ds.split(',');
// Then pass array to Date object with
// spread operator
const d = new Date(...ds);
// Log
console.log(d);
【讨论】:
let [year, month, date, hour, min] = '2018, 07, 01, 10, 0'.split(',');,然后替换您想要的内容,即:month = month.replace(/0(\d)/, '$1');。然后把所有东西放回原处。
在 Javascript Date 对象中,月份从 0 开始到 11,而不是我们习惯的常规 1 到 12 个月。 为了以更好的方式对其进行格式化,您可以使用纯 Javascript。
let now = new Date();
console.log(now); //Sat Jul 25 2020 13:55:30 GMT+0200 (Central European Summer Time)
let normalValues =[now.getFullYear(),now.getMonth()+1,now.getDate(),now.getHours(),now.getMinutes()];
let formated = normalValues.join(",");
console.log(formated); //2020,7,25,13,55
//Explanation for current time 2020/7/25 14:05
now.getFullYear(); //returns 2020
now.getMonth(); //Returns 6, that is why we add one to it to make it 7
now.getDate(); //Returns 25
now.getHours(); //Returns 14
now.getMinutes(); //Returns 5
【讨论】: