最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Add days to Date object and then converting to local string? - Stack Overflow

programmeradmin1浏览0评论

How can i add 5 days to the current date, and then convert it to a string representing the local date and time?

const newDate = new Date();

const test = newDate.setDate(newDate.getDate() + 5).toLocaleString();

Just returns the number of milliseconds.. (same if i use toString().

How can i add 5 days to the current date, and then convert it to a string representing the local date and time?

const newDate = new Date();

const test = newDate.setDate(newDate.getDate() + 5).toLocaleString();

Just returns the number of milliseconds.. (same if i use toString().

Share Improve this question asked Jan 17, 2022 at 16:50 Gambit2007Gambit2007 4,00016 gold badges61 silver badges97 bronze badges 1
  • Does this answer your question? Add days to JavaScript Date – maraaaaaaaa Commented Jan 17, 2022 at 16:54
Add a ment  | 

3 Answers 3

Reset to default 5

Without using any libraries, Vanilla JS solution:

const now = new Date()
const inFiveDays = new Date(new Date(now).setDate(now.getDate() + 5))
console.log('now', now.toLocaleString())
console.log('inFiveDays', inFiveDays.toLocaleString())

This even works when your date overflows the current month.

The easiest way is by using a date library like Moment.js or date-fns. I gave an example below using date-fns and addDays

const newDate = new Date();
const fiveDaysLater = addDays(newDate, 5);

Just use new Date() in front of it.

const newDate = new Date();
const add  =5
const test = newDate.setDate(newDate.getDate() + add)
console.log(new Date(test).toLocaleString());

发布评论

评论列表(0)

  1. 暂无评论