簡體   English   中英

如何使用當前日期添加5天並以moment.js格式格式化輸出?

[英]How to add 5 days with current date and format the output in momentjs?

我面臨將輸出格式化為天/月/年的問題,即(25/08/2019)當我在momentjs中添加5天和當前日期時。

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

輸出:

Sunday at 8:30 PM

但是當我加上10天即:

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

輸出:

08/30/2019

我需要輸出

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

25/08/2019

非常感謝您的幫助。

使用Moment JS的格式化方法

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

moment.calendar 文檔指出:

日歷將使用不同的字符串格式化日期,具體取決於日期與referenceTime的日期(默認為今天)的接近程度。

您可以使用moment().add(5, 'days').format('DD/MM/YYYY')來實現所需的功能。

如果仍然要使用calendar方法 ,我們可以在文檔中看到從2.10.5版本開始,您可以傳遞format參數:

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

Moment's提供的日名( Sunday )介於-6 to 6 ,如果您從當日算起再加上6天,

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

如果您從當日算起再加上-6天,

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

當您將+6加到-6時,它將為您提供日期名稱;如果傳遞的值超過6,它將以MM/DD/YYYY格式返回日期

如果您從當日算起再加上7天,

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

如果您從當日算起再加上-7天,

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

返回查詢...您只需要使用DD/MM/YYYY格式的日期,因此只需要使用.format()方法而不是.calender()

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM