[英]moment unix timestamp formats wrong date
I want to convert an Unix milliseconds timestamp to readable date. 我想将Unix毫秒时间戳转换为可读日期。
My timestamp is 1525772511140. The correct output should be something like: 29-05-2018 9:41:51AM 我的时间戳是1525772511140。正确的输出应该是这样的:29-05-2018 9:41:51 AM
Now my code returns a wrong date: 31-10-50319 03:10... 现在我的代码返回了错误的日期: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)
: 您可以简单地使用
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)与
new Date(Number)
相似,您可以通过传递一个整数值来创建时刻,该整数值表示自Unix纪元(1970年1月1日12 AM 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) : 本机JavaScript解决方案(没有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: 只需从语句中删除
*1000
:
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. 时间戳已经以毫秒为单位,因此无需乘以1000。
None of the answer is giving correct output. 没有答案给出正确的输出。
In question expected output is 29-05-2018 9:41:51AM which is moment().format('DD-MM-YYYY HH:mm:ss A')
有问题的预期输出是29-05-2018 9:41:51 AM这是
moment().format('DD-MM-YYYY HH:mm:ss A')
Below is correct answer as per the question: 以下是根据问题得出的正确答案:
let 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.js"></script>
For more information about moment formats check this link: https://momentjs.com/docs/#/parsing/special-formats/ 有关力矩格式的更多信息,请查看以下链接: https : //momentjs.com/docs/#/parsing/special-formats/
Try 尝试
const date = moment(new Date(1525772511140)).toDate();
or 要么
const date = moment(new Date(1525772511140)).format('DD-MM-YYYY HH:mm')
试试这个
moment.unix(1525772511140 / 1000).format('DD-MM-YYYY HH:mm')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.