9

i'm looking for a way to get the current date and time in the HTTP date format which is for example "Tue, 15 Nov 1994 08:12:31 GMT". I would like to get that with JavaScript. I tried with:

new Date().toString()

but this gives me a different format like: "Tue Aug 20 2013 00:19:28 GMT+0200". I would need to invert the month with the day and put a coma between the day of the week and the day of the month. How can i get that format?

giogix
  • 769
  • 1
  • 12
  • 32

2 Answers2

21

The HTTP date format you mention is actually an RFC-1123 timestamp. The toUTCString function on the Date object is supposed to return a compatible value.

You can validate this with this sample Fiddle.

Niels Keurentjes
  • 41,402
  • 9
  • 98
  • 136
  • 1
    According to [RFC 7231 HTTP/1.1 §7.1.1](https://tools.ietf.org/html/rfc7231#section-7.1.1.1) the "preferred format is a fixed-length and single-zone subset of the date and time specification used by the Internet Message Format [RFC5322]." That may still be compatible, but it requires some more research. – Henry Story Nov 10 '15 at 13:49
0

You can use toLocaleString method with specific parameters and some tweaks. toLocaleString alone can return similar string, but with two commas and without GMT, like Sun, 20 Nov 2022, 12:37:06. So we remove second comma with replace and add missing timezone.

const dateHeader = new Date().toLocaleString('en-GB', {
  timeZone: 'UTC',
  hour12: false,
  weekday: 'short',
  year: 'numeric',
  month: 'short',
  day: '2-digit',
  hour: '2-digit',
  minute: '2-digit',
  second: '2-digit',
}).replace(/(?:(\d),)/, '$1') + ' GMT';

console.log(dateHeader);
Somnium
  • 1,059
  • 1
  • 9
  • 34