Mick
Mick

Reputation: 423

Increment Date Object in without converting to epoch in Javascript

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 :'(

Upvotes: 0

Views: 147

Answers (2)

seriously
seriously

Reputation: 1367

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

Upvotes: 0

RobG
RobG

Reputation: 147413

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.

Upvotes: 1

Related Questions