J. Kelks
J. Kelks

Reputation: 30

How to convert PHP timestamp in JSON to date and time with JavaScript

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?

Upvotes: 0

Views: 512

Answers (2)

DontVoteMeDown
DontVoteMeDown

Reputation: 21465

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).

Upvotes: 1

Callam
Callam

Reputation: 11539

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 })

Upvotes: 0

Related Questions