0

I am trying to use the date function to convert unix time that I am trying to convert to a certain format. The function successfully returns the date in the format requested, but the time is wrong. What am I missing here?

const date = (e) => { 
  const unixTime = 1642698000
  const format = {
    weekday: 'long',
    day: 'numeric', 
    month: "2-digit", 
    year: "numeric"
  }
  return(new Date (unixTime).toLocaleString('en-US', format))
}

Expected output (app.)

Tue Jan 18 2022 17:00:00

The output recieved

Mon Jan 19 1970 19:18:18 GMT-0500 (Eastern Standard Time)

I tried following other exampled but I wasn't able to find any that would resolve this issue. I appreciate your help in advance!

R. Richards
  • 24,603
  • 10
  • 64
  • 64
Amer
  • 57
  • 8

1 Answers1

2

The Date constructor from Javascript accepts the number of milliseconds as timestamp, not unix time (number of seconds). So, to adjust that, is just multiply the unix time by 1000.

const date = () => { 
  const unixTime = 1642698000 * 1000
  const format = {
    weekday: 'long',
    day: 'numeric', 
    month: "2-digit", 
    year: "numeric"
  }
  return(new Date (unixTime).toLocaleString('en-US', format))
}

console.log(date())
// logs Thursday, 01/20/2022
  • 1
    You should avoid answering questions that are already answered. An exception might be if the question is only partially a duplicate, but even then you should reference the duplicate questions for that part that is clearly a duplicate. – t.niese Jan 17 '22 at 20:57