0

I am currently working on a project that will be updating data locally to a JSON file so if there is ever an issue where we can't access our API for data we will load the local JSON file. The issue I am running into now is actually getting a correct timestamp the user will see to know when the information was last updated. I am able to get the date to come back correctly but it always comes back as a UTC string that I'm not sure how to convert to my timezone. The code I currently have looks like this:

function fetchHeader(url: string, headerResponse: string): any {
  const req = new XMLHttpRequest();
  req.open("HEAD", url, false);
  req.send(null);
  return req.getResponseHeader(headerResponse);
}

This always returns the date as:

Mon, 05 Jun 2023 16:17:06 GMT

I know this is the correct UTC date and time but I haven't found many resources on how to get back the non string version of this header to convert back to my local timezone. I know the tz function is available on a Date variable but since this is purely a string I'm not sure how to go about converting it.

JayPee
  • 17
  • 4
  • Likely something useful [in stack overflow](https://stackoverflow.com/search?q=%5Bjavascript%5D+convert+string+to+date) with many details in [this question](https://stackoverflow.com/questions/5619202/parsing-a-string-to-a-date-in-javascript) – freedomn-m Jun 05 '23 at 17:27
  • When you parse a string into a date, it will store as UTC - then when you *display* the date it will be your local time. – freedomn-m Jun 05 '23 at 17:28

1 Answers1

0

The JS Date constructor should be able to take that string in, i.e.: let headerDate = new Date('Mon, 05 Jun 2023 16:17:06 GMT'); should create a date object, then you can either just print pop it into a string, or use headerDate.toLocaleDateString() to format it how you'd like.

Travis
  • 316
  • 1
  • 13