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

javascript - How to add 5 days with current date and format the output in momentjs? - Stack Overflow

programmeradmin7浏览0评论

I am facing problem to format the output as days/mon/years i.e ( 25/08/2019) when I add 5 days with the current date in momentjs.

console.log( moment().add(5, 'days').calendar());

Output:

Sunday at 8:30 PM

But when I add 10 days i.e:

console.log( moment().add(10, 'days').calendar());

Output:

08/30/2019

I need the output for

moment().add(5, 'days').calendar() 

as

25/08/2019

I will highly appreciate your help.

I am facing problem to format the output as days/mon/years i.e ( 25/08/2019) when I add 5 days with the current date in momentjs.

console.log( moment().add(5, 'days').calendar());

Output:

Sunday at 8:30 PM

But when I add 10 days i.e:

console.log( moment().add(10, 'days').calendar());

Output:

08/30/2019

I need the output for

moment().add(5, 'days').calendar() 

as

25/08/2019

I will highly appreciate your help.

Share Improve this question asked Aug 20, 2019 at 14:39 Ben JonsonBen Jonson 7391 gold badge10 silver badges31 bronze badges 0
Add a ment  | 

3 Answers 3

Reset to default 4

Use format method of moment js

moment().add(5, 'days').format('DD/MM/YYYY') 

The moment.calendar documentation states that:

Calendar will format a date with different strings depending on how close to referenceTime's date (today by default) the date is.

You can use moment().add(5, 'days').format('DD/MM/YYYY') to achieve what you want.

If you still want to use the calendar method, we can see in the documentation that from version 2.10.5 you can pass a format parameter:

moment().add(5, 'days').calendar(null, {
    sameDay: '[Today]',
    nextDay: '[Tomorrow]',
    nextWeek: 'dddd',
    lastDay: '[Yesterday]',
    lastWeek: '[Last] dddd',
    sameElse: 'DD/MM/YYYY'
})

Moment's provide a day name (Sunday)in range of -6 to 6, If you add 6 days from the current day it will be

moment().add(6, 'days').calendar();
// "Monday at 8:17 PM"

If you add -6 days from current day it will be

moment().add(-6, 'days').calendar();
// "Last Wednesday at 8:17 PM"

It will give you name of day when you add up to +6 to -6, If you pass more than 6 it returns the date in MM/DD/YYYY format

If you add 7 days from the current day it will be

moment().add(7, 'days').calendar();
// "08/27/2019"

If you add -7 days from current day it will be

moment().add(-7, 'days').calendar();
// "08/13/2019"

Back to your query...You only need a date in the format of DD/MM/YYYY, So you just need to use .format() method instead of .calender()

moment().add(6, 'days').format('DD/MM/YYYY');
发布评论

评论列表(0)

  1. 暂无评论