I want to convert an Unix milliseconds timestamp to readable date.
My timestamp is 1525772511140. The correct output should be something like: 29-05-2018 9:41:51AM
Now my code returns a wrong date: 31-10-50319 03:10...
code:
var timeStamp = new Date(1525772511140 * 1000);
var date = moment(timeStamp).format('DD-MM-YYYY HH:mm');
console.log(date);
You can simply use moment(Number):
Similar to
new Date(Number), you can create a moment by passing an integer value representing the number of milliseconds since the Unix Epoch (Jan 1 1970 12AM UTC)
var date = moment(1525772511140).format('DD-MM-YYYY HH:mm');
console.log(date);
// with seconds and AM/PM
date = moment(1525772511140).format('DD-MM-YYYY hh:mm:ss A');
console.log(date);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.1/moment.min.js"></script>
Native JavaScript solution (without moment.js) :
var d = new Date(1525772511140);
console.log(
("0" + d.getDate()).slice(-2) + '-' +
("0" + (d.getMonth()+1)).slice(-2) + '-' +
d.getFullYear() + ' ' +
d.getHours() + ':' +
d.getMinutes()
);
Just remove the *1000 from your statement and it works:
var timeStamp = new Date(1525772511140);
var date = moment(timeStamp).format('DD-MM-YYYY HH:mm');
console.log(date);
<script src="https://cdn.jsdelivr.net/momentjs/latest/moment.min.js"></script>
The timestamp is already in milliseconds so no need to multiply by 1000.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With