Javascript日期加2周(14天)

jQu*_*ast 28 javascript date

我用它来得到日期:

var currentTime = new Date()
var month = currentTime.getMonth() + 1
var day = currentTime.getDate()
var year = currentTime.getFullYear()
alert(month + "/" + day + "/" + year);
Run Code Online (Sandbox Code Playgroud)

我该如何添加2周?因此,而不是显示10/13/2011,显示10/27/2011等

这是小提琴:http://jsfiddle.net/25wNa/

我希望一个输入有+14天而另一个+21

注意:我希望格式为> 10/13/2011 <.

ale*_*lex 71

12096e5是一个神奇的数字,是14天,以毫秒为单位.

var fortnightAway = new Date(Date.now() + 12096e5);
Run Code Online (Sandbox Code Playgroud)

jsFiddle.

  • @jQuerybeast:`1000*60*60*24*14`,*毫秒,一秒钟*秒,一分钟*分钟,一小时*一小时*一天*天,2周*. (3认同)

YuS*_*YuS 30

var currentTime = new Date();
currentTime.setDate(currentTime.getDate()+14);
Run Code Online (Sandbox Code Playgroud)


Pra*_*van 11

为你做了一个蠢货http://jsfiddle.net/pramodpv/wfwuZ/

    Date.prototype.AddDays = function(noOfDays) {
       this.setTime(this.getTime() + (noOfDays * (1000 * 60 * 60 * 24)));
       return this;
    }

    Date.prototype.toString = function() {
       return this.getMonth() + "/" + this.getDate() + "/" +  this.getFullYear().toString().slice(2); 
    }

    $(function() {
        var currentTime = new Date();
        alert(currentTime.AddDays(14));
    });
Run Code Online (Sandbox Code Playgroud)


小智 9

试试这个:

currentTime.setDate(currentTime.getDate()+14);
Run Code Online (Sandbox Code Playgroud)


Ogn*_*rov 8

12096e5一种神奇的数字.以指数表示法几毫秒内完成 14天.

该数字是以指数表示法保存1000 [ms]*60 [s]*60 [m]*24 [h]*14 [d]的结果.

如果键入Number('12096e5'),可以检查它.您将获得1209600000 [ms],这正好是2周(以毫秒为单位).指数表示法使其模糊不清.

您可以用指数表示法编写任何其他数字,以使您的开发人员的生活更有趣.

Date对象具有构造函数,该构造函数接受毫秒作为参数,该参数可以是指数表示法.

var d = new Date(毫秒);

var afterTwoWeeks = new Date(+new Date + 12096e5);
var afterTwoWeeks = new Date(+new Date + 1209600000);
Run Code Online (Sandbox Code Playgroud)

两者都是一样的.

  • *幻数*[维基百科](https://en.wikipedia.org/wiki/Magic_number_(编程)) (3认同)

Spu*_*ley 5

嗯,JS 时间以毫秒为单位,因此添加两周就是计算出两周以毫秒为单位,然后添加该值的情况。

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

当然,如果您需要添加月份,则此方法会失败,因为它们的长度是可变的,但添加天和周就可以了。

或者,您可以使用DateJS 库,它具有此类功能(并且可以加载更多)。

使用 DateJS,您的代码可能如下所示:

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

希望有帮助。