Bennett
Bennett

Reputation: 1107

Parse If-Modified-Since Header (node.js)

I am trying to implement sending a 304 header for performance in a server hosting program I am writing, but I do not know how to parse the date of the If-Modified-Since header. I also would like to know how to find out if the If-Modified-Since date is older/newer than another date that I have in my code.

Upvotes: 3

Views: 3495

Answers (2)

Bennett
Bennett

Reputation: 1107

To parse the date, use new Date(datestring) or Date.parse(datestring). To see if a date is newer or older than another date, use the greater than (>) and less than (<) operators.

Upvotes: 3

Pavel P
Pavel P

Reputation: 16843

Just in case if someone comes across...

  • To parse date from "Last-Modified" you can use Date constructor that takes a date string.
  • You can also use Date.parse, which returns number of milliseconds since epoch (for invalid dates it returns NaN).
  • To print back date in format suitable for "Last-Modified" or "If-Modified-Since" header you can use Date's toUTCString() method.

var date = new Date("Wed, 17 May 2017 04:44:36 GMT");
var ms = Date.parse("Wed, 17 May 2017 04:44:36 GMT");
console.log('parsed date: ', date);
console.log('parsed date ms: ', ms);
console.log('If-Modified-Since: '+date.toUTCString());

Upvotes: 6

Related Questions