添加并休息一天到日期字符串



我有一个日期,可以是日期或日期时间,例如:2021-04-13

2021-04-1400:00:00.000Z

两者都是字符串,所以我需要在每个日期上加或减一天,但如果一个日期是一个月的最后一天,我加一天,那么我需要更改月份,如果是一个月中的最后一个月,则需要更改年份,并且我需要减到该月第一天的日期也是如此。我正在使用打字

在评论中澄清后,我确信这会达到你想要的效果:

function modifyDate(input: string, dayModification: number): string {
// regex that will match ####-##-## where # is a number
const isDateOnlyRegex = /^d{4}-d{2}-d{2}$/;
// javascript will natively understand both formats when parsing a string to Date
const date = new Date(input);
// add the dayModification value as days to the date
date.setDate(date.getDate() + dayModification);
// check if it's a dateOnly string
if (isDateOnlyRegex.test(input)) {
// using string format to return yyyy-MM-dd format
return `${date.getFullYear()}-${date.getMonth()+1}-${date.getDate()}`;
}
// date.toJSON returns yyyy-MM-ddTHH:mm:ss.SSSZ
// could also use date.toISOString
return date.toJSON();
}

在此处测试(单击顶部的Run以获得控制台输出(

您可以使用moment.jsadd减法方法。

Ex。

import moment from 'moment'
const date: string = "2021-04-30";
console.log(moment(date).add(1, "d"));
console.log(moment(date).subtract(10, "d"));

检查文档

您可以使用valueOf()根据自1970年1月1日00:00:00 UTC以来的毫秒数创建一个新日期,并将其偏移要添加的天数(以毫秒为单位(来实现这一点。

参见以下示例:

function addDays(date, days) {
return new Date(
date.valueOf()                 // convert to milliseconds
+ days * 24 * 60 * 60 * 1000   // add number of days in milliseconds
)
}
// long date
let date = new Date('2021-04-14T00:00:00.000Z');
console.log(addDays(date, 1));
console.log(addDays(date, -1));
// short date
date = new Date('2021-04-14');
// different month
console.log(addDays(date, 20));
console.log(addDays(date, -20));

// different year
console.log(addDays(date, 320));
console.log(addDays(date, -320));

将其转换为时间戳

添加1天时间戳到

day = 60 * 60 * 24 * 1000;

最新更新