Javascript Date Plus 2 Weeks (14 days)
Asked Answered
C

9

53

I use this to get the date:

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

How can I add 2 weeks ? So instead of showing 10/13/2011, to show 10/27/2011 etc

Here is the fiddle: http://jsfiddle.net/25wNa/

I want the one input to have +14 days and the other +21

Note: I'd like the format to be > 10/13/2011 <.

Cerulean answered 13/10, 2011 at 9:19 Comment(1)
Please, use the ISO date format: YYYY-MM-DD xkcd.com/1179Marvellamarvellous
M
122

12096e5 is a magic number which is 14 days in milliseconds.

var fortnightAway = new Date(Date.now() + 12096e5);

jsFiddle.

Mariannamarianne answered 13/10, 2011 at 9:23 Comment(12)
@jQuerybeast: It doesn't for me.Mariannamarianne
Ah my mistake. I want it on my format that's why I asked the question. Can you check my fiddle and the edit? ThanksCerulean
@Cerulean Simply use your existing code, but replace currentTime with fortnightAway.Mariannamarianne
Where have you got the 12096e5 from? Like in case I want to add more days etc.Cerulean
@jQuerybeast: 1000 * 60 * 60 * 24 * 14, milliseconds in one second * seconds in a minute * minutes in an hour * hours in a day * days in 2 weeks.Mariannamarianne
Have you noticed that if you add more than 14 days, the month doesn't change?Cerulean
@Cerulean I doubt that, do you have a fiddle?Mariannamarianne
@Cerulean You are adding a month to a and using that when in both inputs. That's why it's the same month - it's the same variable.Mariannamarianne
@Mariannamarianne Is this really robust, though? Like when a day is not strictly 24 hours, like happened recently?Demetri
A day isn't strictly 24 hours, but I believe it's safe to measure them at 24 hours.Mariannamarianne
As commented below: if you want to handle DST -> function addDays(noOfDays, date) { var origTimezoneOffset = date.getTimezoneOffset(); date = new Date(date.getTime() + (noOfDays * (1000 * 60 * 60 * 24))); var offsetDiff = (date.getTimezoneOffset() - origTimezoneOffset) * 60 * 1000; date = new Date(date.getTime() + offsetDiff); return date; }Auguste
What if want to increase number of days??Colorimeter
S
54
var currentTime = new Date();
currentTime.setDate(currentTime.getDate()+14);
Shaunta answered 13/10, 2011 at 9:25 Comment(4)
Can you please check my edit? Id like it in a format of DD/MM/YY. That's why I asked my question because if I add on that format it bypasses the maximum days of a month. I get a value of 34/10/2011. ThanksCerulean
Just put currentTime.setDate(currentTime.getDate()+14); before you defining separate day, month and year variables in your function. It should works.Shaunta
Does this work if adding 14 days would put you in the next month?Pomatum
@NathanArthur Surprisingly, it does work for any number of months/years after/agoSolidary
M
11

have made a fidle for you 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));
    });
Miry answered 13/10, 2011 at 9:25 Comment(4)
Can you please check my edit? Id like it in a format of DD/MM/YY. That's why I asked my question because if I add on that format it bypasses the maximum days of a month. I get a value of 34/10/2011. ThanksCerulean
if you are using the DD/MM/YY throughout you can override the dates toString function. i have edited my answer and fiddle as per your date format. js fiddle link is jsfiddle.net/pramodpv/wfwuZ/2Miry
I liked the AddDays function, however it does not handle dst switches if you want that: So, I made it more like this: function addDays(noOfDays, date) { var origTimezoneOffset = date.getTimezoneOffset(); date = new Date(date.getTime() + (noOfDays * (1000 * 60 * 60 * 24))); var offsetDiff = (date.getTimezoneOffset() - origTimezoneOffset) * 60 * 1000; date = new Date(date.getTime() + offsetDiff); return date; }Auguste
Overwriting Date.prototype.toString() is probably a bad ideaMariannamarianne
V
11

Try this:

currentTime.setDate(currentTime.getDate()+14);
Vaso answered 13/10, 2011 at 9:27 Comment(0)
M
11

12096e5 is a kind of magic number. Just 14 days in milliseconds in exponential notation.

This number is the result of 1000[ms] * 60[s] * 60[m] * 24[h] * 14[d] saved in exponential notation.

You can check it if you type Number('12096e5'). You will get 1209600000 [ms] which is exactly 2 weeks in milliseconds. The exponential notation makes it obscure.

You can write any other number in exponential notation to make the life of your fellow developers more interesting.

Date object has constructor which accepts milliseconds as an argument which argument can be in exponential notation.

var d = new Date(milliseconds);

var afterTwoWeeks = new Date(+new Date + 12096e5);
var afterTwoWeeks = new Date(+new Date + 1209600000);

Both are the same.

Minded answered 19/10, 2017 at 8:43 Comment(3)
Magic number WikipediaMariannamarianne
Note that exponential notation is not a real-world example in the Wikipedia reference to magic numbers nor is it an example in a protocol, since it is one number defined in exponential notation as Ognyan pointed outThames
@Mariannamarianne I agree that to a large extent this is a magic number/string. It is magic 'literal' but since the confusion comes from the type of notation I wrote that it is not a magic literal which was not correct.Minded
C
5

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.

Consecutive answered 13/10, 2011 at 9:25 Comment(7)
I think var twoWeeks = 1000* 60 * 60 * 24 * 14;Trachoma
Can you please check my edit? Id like it in a format of DD/MM/YY. That's why I asked my question because if I add on that format it bypasses the maximum days of a month. I get a value of 34/10/2011. ThanksCerulean
@Cerulean - using the technique from your the question with the twoWeeksTime variable in my answer will give you a valid date. Have you tried it? But anyway, I've added a formatting line of code to my answer, plus a bit of code to demo how the DateJS makes things easier.Consecutive
@Cerulean - fair enough; I've given you an equally good bit of code that doesn't use a plugin.Consecutive
@Cerulean - ironically, your JSFiddle goes to an error 404. But yes, I have tested it... and you're right, I had forgotten to add the +1 to the month, but since you already had that in the code in your question, I guess you're smart enough to have worked out where I went wrong. (I've now added the +1 though)Consecutive
@spudley +1 on the month makes no difference if it works or not. Since it wasn't compiling I couldn't check if its 1 month behind to change that. It is just not compiling. jsfiddle.net/FQzbz I am not THAT good at JavaScript and that's probably why I am asking this question in the first place?Cerulean
well, I don't know what you're doing different to me, but I can paste those three lines of code into Firebug followed by alert(formattedDate);, and it gives me the correct date for two weeks time. Here's a working JSFiddle: jsfiddle.net/KXMExConsecutive
B
2

Add or Subtract 2 weeks from current date

Below code example give output in YYYY-MM-DD format

If condition is added in the string to concatenate 0 with Month and Day which is less than 10.

var twoWeeks = 1000 * 60 * 60 * 24 * 14;
var twoWeeksTime = new Date(new Date().getTime() + twoWeeks); /* Add or Subtract here*/

var formattedDate = (twoWeeksTime.getFullYear()) + '-' +
                    ((twoWeeksTime.getMonth()+1) < 10 ? "0"+(twoWeeksTime.getMonth()+1): (twoWeeksTime.getMonth()+1)) + '-' +
                    (twoWeeksTime.getDate() < 10 ? "0"+(twoWeeksTime.getDate()): (twoWeeksTime.getDate()));

document.body.innerHTML = formattedDate;
Bias answered 2/2, 2021 at 12:8 Comment(0)
D
0

add the following prototype method

Date.prototype.addDays = function(days) {
     this.setDate(this.getDate()+days);
}

and than its very simple to use,

currentTime.addDays(5);
Denounce answered 13/10, 2011 at 9:25 Comment(0)
T
-1

If you are formatting a javascript date in a particular format, then I think you can have a look at this script http://blog.stevenlevithan.com/archives/date-time-format. All you would need to do after including the script is this new Date(+new Date + 1000* 60 * 60 * 24 * 14).format('dd/mm/yyyy') and you would get the output "27/10/2011"

The script is pretty small, just above 1KB minified. This is the link to a working fiddle http://jsfiddle.net/naryad/GufvT/

Trachoma answered 13/10, 2011 at 9:42 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.