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?

vijoc
  • 683
  • 8
  • 17
J. Kelks
  • 30
  • 3
  • possible duplicate https://stackoverflow.com/questions/14350148/convert-ticks-to-time-format-hhmmss – Prasad Telkikar Nov 06 '18 at 10:42
  • https://www.toptal.com/software/definitive-guide-to-datetime-manipulation – Naveen Kulkarni Nov 06 '18 at 10:43
  • 1
    *"How can i turn this in days"* what do you mean by that? a timestamp is the number of seconds *(in PHP)* since 1.1.1970. Do you want the number of days since then? or the day of the month? or what kind of *"days"*? – Thomas Nov 06 '18 at 10:58
  • 1
    Possible duplicate of [Convert a Unix timestamp to time in JavaScript](https://stackoverflow.com/questions/847185/convert-a-unix-timestamp-to-time-in-javascript) – Jesse Nov 06 '18 at 11:02

2 Answers2

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

DontVoteMeDown
  • 21,122
  • 10
  • 69
  • 105
  • 1
    PHP uses seconds for its timestamps, whereas JS uses milliseconds. You have to `*1000` – Thomas Nov 06 '18 at 10:54
  • 1
    @Thomas sorry but where did you see [tag:php] ? – DontVoteMeDown Nov 06 '18 at 11:05
  • 2
    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 Nov 06 '18 at 11:10
  • @Thomas you're right, that was my bad. Indeed, a very useful comment to the subject. Tks – DontVoteMeDown Nov 06 '18 at 11:37
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 })
Callam
  • 11,409
  • 2
  • 34
  • 32