2

I wrote the following code in JS

var d = new Date(2019, 9, 14);

var currentTime = d.getTime();
var daysToAdd = 3;

var secondsInDay = 86400;

var d = new Date(currentTime + daysToAdd*secondsInDay);

var year = d.getFullYear();
var month = ("0" + (d.getMonth())).slice(-2);
var day = ("0" + d.getDate()).slice(-2);

console.log('result in Y-M-D is: ' + year + '-' + month + '-' + day);

This outputs to result in Y-M-D is: 2019-09-14

What am I doing wrong here? How to I change this to output result in Y-M-D is: 2019-09-17 , which I originally intended to do

3
  • 2
    you need to add milliseconds.... daysToAdd*secondsInDay*1000 Check the details developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… Commented Oct 16, 2018 at 0:48
  • One other issue you will come up against ... you're setting new Date(2019, 9, 14) - this, as you know is actually, 14th October 2019 - however, the output string you want to create is 2019-09-17 - which would imply 17th September 2019 - perhaps not what you intended Commented Oct 16, 2018 at 0:57
  • Yes sorry that was a silly mistake. Thanks Commented Oct 16, 2018 at 1:37

4 Answers 4

3

This happens because on this code

new Date(currentTime + daysToAdd*secondsInDay);

secondsInDay is a representation in seconds, and currentTime is represented in ms. If you multiply your secondsInDay by 1000 (to get the equivalent value in ms) you will get the desired date.

Sign up to request clarification or add additional context in comments.

Comments

3

Instead of

var d = new Date(currentTime + daysToAdd*secondsInDay);

you can use

d.setDate(new Date().getDate()+3);

Comments

0

Youre problem is that the constructor of the date object uses MILISECONDS to calculate the date, and you're using SECONDS to add that 3 extra days. Instead of 86400 (seconds) you need to use the value 86400000 (miliseconds).

Goodbye!

Comments

0

You can add the number of days directly to d.getDate()

var d = new Date(2019, 9, 14);
  var daysToAdd = 3;
  var new_day = d.getDate() + daysToAdd;
  var new_d = new Date(d.getFullYear(), d. getMonth(), new_day);

  alert('result in Y-M-D is: ' + new_d.getFullYear() + '-' + new_d. getMonth() + '-' + new_day);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.