Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert 17-digit precision unix time (UTC) to date fromat In javascript

I got time token like this from 14512768065185892 from PubNub.I need to convert this time token into following format dd/mm/yy.

Any one please provide one method to convert time stamp to date format.

Thanks In Advance

like image 803
Kichu Avatar asked Dec 14 '22 09:12

Kichu


2 Answers

The Date constructor can be passed a time value that is milliseconds since the epoch (1970-01-01T00:00:00Z). The value you have seems to have 4 digits too many, so just divide by 1e4 (or whatever value is appropriate):

var timeValue = 14512768065185892;
document.write(new Date(timeValue/1e4));

There are plenty of questions and answers here on how to format the output as dd/mm/yy (which is a very ambiguous format), e.g.

function formatDMYY(d) {
  function z(n){return (n<10?'0':'') + n}
  return z(d.getDate()) + '/' + z(d.getMonth() + 1) + '/' + z(d.getFullYear()%1e3);
}

document.write(formatDMYY(new Date(14512768065185892/1e4)));
like image 89
RobG Avatar answered Jan 26 '23 00:01

RobG


You can just remove the last 4 characters, and use this timestamp in Date constructor:

new Date(+str.substr(0, str.length - 4))  

However, JS doesn't support "dd/mm/yyyy" format, and you will have to implement it yourself or use third-party libraries like Moment.js.

Here is the working demo:

Date.parsePubNub = function(str) {
    return new Date(+str.substr(0, str.length - 4));
};

Date.prototype.toDDMMYYYY = function()
{
  return ("0" + this.getDate()).slice(-2) + "/" + ("0" + (this.getMonth() + 1)).slice(-2) + "/" + this.getFullYear();
};

var str = "14512768065185892";
document.body.innerText = Date.parsePubNub(str).toDDMMYYYY();
like image 43
Yeldar Kurmangaliyev Avatar answered Jan 25 '23 23:01

Yeldar Kurmangaliyev