azrael v
azrael v

Reputation: 281

Why am I getting this error for JavaScript Date object?

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

Upvotes: 2

Views: 357

Answers (4)

Erlisar Vasquez
Erlisar Vasquez

Reputation: 460

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);

Upvotes: 0

FlokiTheFisherman
FlokiTheFisherman

Reputation: 234

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!

Upvotes: 0

Narendra
Narendra

Reputation: 4574

Instead of

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

you can use

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

Upvotes: 3

Andre Knob
Andre Knob

Reputation: 831

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.

Upvotes: 3

Related Questions