Convert string to date and add 5 days to it

。_饼干妹妹 提交于 2021-02-05 12:00:45

问题


I have a string like so

"2014-10-29"

and Now I need to convert it to a date and add 5 days to it.

I have this code that adds 5 days to the current date, but how would I convert that string to a date and add 5 days to it?

var newDate = new Date();
newDate.setDate(newDate.getDate() + 5);

var yyyy = newDate.getFullYear().toString();
var mm = (newDate.getMonth() + 1).toString();
var dd = newDate.getDate().toString();

var mmChars = mm.split('');
var ddChars = dd.split('');

var newClosingDate = yyyy + '-' + (mmChars[1] ? mm : "0" + mmChars[0]) + '-' + (ddChars[1] ? dd : "0" + ddChars[0]);

回答1:


Pass the string in to the Date constructor:

var newDate = new Date("2014-10-29");
newDate.setDate(newDate.getDate() + 5);

var yyyy = newDate.getFullYear().toString();
var mm = (newDate.getMonth() + 1).toString();
var dd = newDate.getDate().toString();

var mmChars = mm.split('');
var ddChars = dd.split('');

var newClosingDate = yyyy + '-' + (mmChars[1] ? mm : "0" + mmChars[0]) + '-' + (ddChars[1] ? dd : "0" + ddChars[0]);

console.log(newDate);



回答2:


You could also use the wonderful library called moment.js - it makes working with dates in JavaScript an absolute breeze. Especially converting them back and forth to/from strings.

With your date and using moment, you could do this for example:

var stringFormat = 'YYYY-MM-DD', 
    date = moment('2014-10-29', 'YYYY-MM-DD');

date.add(5, 'days');

console.log(date.format(stringFormat);

This will print out the string in the same format as you put in.



来源:https://stackoverflow.com/questions/33921403/convert-string-to-date-and-add-5-days-to-it

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!