Javascript Date Plus 2 Weeks (14 days)

后端 未结 8 1774
孤街浪徒
孤街浪徒 2020-12-05 17:00

I use this to get the date:

var currentTime = new Date()
var month = currentTime.getMonth() + 1
var day = currentTime.getDate()
var year = currentTime.getFu         


        
8条回答
  •  庸人自扰
    2020-12-05 17:37

    Well, JS times are in millisecond, so adding two weeks would be a case of working out what two weeks is in milliseconds, and adding that value.

    var twoWeeks = 1000 * 60 * 60 * 24 * 14;
    var twoWeeksTime = new Date(new Date().getTime() + twoWeeks);
    var formattedDate = twoWeeksTime.getDate() + '/' + (twoWeeksTime.getMonth()+1) + '/' + twoWeeksTime.getYear();
    

    Of course, this method falls down if you need to add months, since they're variable in length, but it's fine for adding days and weeks.

    Alternatively, you use the DateJS library, which has functionality for exactly this kind of thing (plus loads more).

    With DateJS, your code could look like this:

    var twoWeeksTime = Date.today().add({ days: 14 });
    var formattedDate = twoWeeks.TimetoString('dd/MM/yy');
    

    Hope that helps.

提交回复
热议问题