0

Is it possible to increment a date object by one day without converting the object to an epoch number?

For example the traditional way will convert the date object to an epoch number:

var today = new Date();
var tomorrow = new Date(today.valueOf()); // copy date object without converting to epoch
tomorrow.setDate(tomorrow.getDate() + 1); // now gets converted to epoch :'(
Mick
  • 413
  • 4
  • 14
  • 1
    Does this answer your question? [Add days to JavaScript Date](https://stackoverflow.com/questions/563406/add-days-to-javascript-date) – zcoop98 Jun 10 '21 at 22:29

2 Answers2

1

The set* methods don't "convert to epoch number", they modify the date's internal time value and return the modified value. The date object is still a date.

let today = new Date();
today.setHours(0,0,0,0); // Start of day
let tvToday = +today;
let tomorrow = new Date(today);
// setDate adjusts the time value and returns it
let tvTomorrow = tomorrow.setDate(tomorrow.getDate() + 1);

console.log('Today\'s date: ' + today.toDateString());
console.log('Today\'s time value: ' + tvToday);

console.log('Tomorrow\'s date: ' + tomorrow.toDateString());
console.log('Tomorrow\'s time value: ' + tvTomorrow);

// May vary from 24 by up to 1 hour depending on crossing DST boundaries
console.log('Difference in hours: ' + ((tvTomorrow - tvToday)/3.6e6)); 

If you want a method that adds a day and returns a new Date object, write a function, maybe named addDays, that takes a date and number of days to add and returns a new Date object with the days added. Lots of libraries have such functions, they're not hard to write.

RobG
  • 142,382
  • 31
  • 172
  • 209
0

Not sure if you can do that without converting. Maybe convert back after.

var today = new Date();
var tomorrow = new Date(today.valueOf());

const x = tomorrow.setDate(tomorrow.getDate() + 1);
console.log(x) //epoch

const z = new Date(x)
console.log(z.toString())
Spectric
  • 30,714
  • 6
  • 20
  • 43
seriously
  • 1,202
  • 5
  • 23