0

I have in my JSON file a timestamp for every user login, for example:

timestamp: "1541404800"

How can I turn this to a date and time?

4

2 Answers 2

1

You can instantiate a Date object with that value in the parameter:

var convertedTimestamp = 1541404800 * 1000; // From Unix Timestamp to Epoch time
var date = new Date(convertedTimestamp);
console.log(date);
// Result: A Date object for "2018-11-05T08:00:00.000Z"

Remember to convert your Unix timestamp time to Epoch time in order to get the right time(mode here).

Sign up to request clarification or add additional context in comments.

4 Comments

PHP uses seconds for its timestamps, whereas JS uses milliseconds. You have to *1000
@Thomas sorry but where did you see php ?
I don't see PHP anywhere. I know from PHP that is uses timestamps in seconds. I don't know what other backend language uses timestamps in seconds, but the number 1541404800 is obviously way too small (in the context of the question asked) to be a timestamp in milliseconds as it would be used in JS. And 2018-11-05T08:00:00.000Z seems more likely that some Date in 1970. Sry, I see now that the way I phrased the comment was misleading.
@Thomas you're right, that was my bad. Indeed, a very useful comment to the subject. Tks
0

function componentsForDate(date) {
  return {
    d: date.getDate(),
    h: date.getHours(),
    m: date.getMinutes(),
    s: date.getSeconds(),
  };
}

function dayDifferenceForDate(date) {
  const secDiff = Math.abs(Date.now() - date.getTime());
  const dayDiff = Math.ceil(secDiff / (1000 * 3600 * 24));

  return dayDiff;
}

const date = new Date(1541404800 * 1000)
const comps = componentsForDate(date)
const dayDiff = dayDifferenceForDate(date) 

console.log({ comps, dayDiff })

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.