roger's picture

Subtracting dates in Javascript

Here's how to find the time 30 minutes ago:

var THIRTY_MINUTES_IN_MS = 30 * 60 * 1000;

var now = new Date();
var nowMs = now.getTime();
    
var thenMs = nowMs - THIRTY_MINUTES_IN_MS;
var then = new Date(thenMs);

The secret is that Date.getTime returns the number of milliseconds since the epoch, and that the Date constructor accepts these millisecond values.

Reply

The content of this field is kept private and will not be shown publicly.
  • Allowed HTML tags: <a> <b> <br> <code> <dd> <dl> <dt> <hr> <h1> <h2> <h3> <i> <img> <li> <ol> <p> <pre> <table> <td> <th> <tr> <tt> <u> <ul>
  • Images can be added to this post.

More information about formatting options