dpDesignz
dpDesignz

Reputation: 1957

Adding to Epoch to find new Date in Javascript

I'm working on a response from a script to work out an expiry date. The response is 7200 which I've been advised from the developer is an epoch value that should equate to 3 months. I've never used Epoch before so don't understand how this works?

The formula I've been given to use is (created_at + expires_in) * 1000 which I've been advised will give me my new date.

I used dtmNow = new Date(Date.now()).toISOString(); which returned 2016-08-23T06:33:35.936Z which was correct, but when I tried dtmExpires = new Date((Date.now()+7200)*1000).toISOString(); it returned +048613-09-25T09:58:58.000Z?

I'm not sure what I'm doing wrong here?

Upvotes: 1

Views: 1487

Answers (1)

RobG
RobG

Reputation: 147543

Date.now() returns the number of milliseconds since the epoch (the current time value). If you pass a number to the Date constructor, it's used as the time value for a new Date instance. In the following:

new Date(Date.now()).toISOString()

is exactly the same as:

new Date().toISOString()

i.e. you don't need Date.now(). If you want to add 3 months to a date, use Date methods:

// Get a Date for now
var now = new Date();

// Add 3 months
now.setMonth(now.getMonth() + 3);

However, if it's currently 30 November then the above will attempt to create a date for 30 February, which will end up being 1 or 2 March depending on whether it's a in a leap year or not. So if the modified day in the month doesn't match the original, you can set it back to the last day of the previous month.

If you want to add (say) 90 days, then do that using the setDate and getDate methods similar to the following. This also takes account of daylight saving boundaries if you cross one, whereas setting the time value doesn't.

The SO console writes dates in UTC so take that into account when looking at the following results:

function add3Months(d) {
  // Default to current date if d not provided
  d = d || new Date();
  
  // Remember current date
  var date = d.getDate();
  
  // Add 3 months
  d.setMonth(d.getMonth() + 3);
  
  // Set the date back to the last day of the previous
  // month if date isn't the same
  if (d.getDate() != date) d.setDate(0);
  
  return d;
}

// Add 3 months to today
console.log(add3Months());

// Add 3 months to 30 November
console.log(add3Months(new Date(2016,10,30)))

Upvotes: 1

Related Questions