简体   繁体   English

如何在Node JS中将大数转换为普通数?

[英]How to convert a big number to normal in node js?

I receive my data in which there is: 我收到的数据包括:

deviceTimestamp:1531564520188828

I want to convert this timestamp in human date and use this code: 我想将此时间戳转换为人类日期并使用以下代码:

moment.unix(timestamp).format('dddd, MMMM Do, YYYY h:mm:ss A');

But when I console.log(deviceTimestamp), it returns me this 但是当我console.log(deviceTimestamp),它返回我

BigNumber { s: 1, e: 15, c: [ 15, 31656237268093 ] },

And timestamp convert does not work. 和时间戳转换不起作用。

IMHO, you are trying to do something like this: 恕我直言,您正在尝试执行以下操作:

 deviceTimestamp = 1531564520188828; var d = new Date(deviceTimestamp); console.log(d); console.log(d.getDate() + '/' + (d.getMonth()+1) + '/' + d.getFullYear()); var dateString = d.toGMTString(); console.log(dateString); 

NOTE : 注意

  • It seems like an incorrect timestamp hence, the invalid year. 似乎是错误的时间戳,因此是无效的年份。
  • This is an approach using Vanilla JS. 这是使用Vanilla JS的方法。

The number you have appears to be micro seconds since midnight 1st January 1970. 自1970年1月1日午夜以来,您所看到的数字是微秒。

Forget the Unix timestamp and divide the number you have by 1,000 for the JavaScript timestamp. 忘记Unix时间戳记,然后将JavaScript时间戳记除以1,000。

 var deviceTimestamp = 1531564520188828; var date = moment(deviceTimestamp/1000).format('dddd, MMMM Do, YYYY h:mm:ss A'); console.log(date); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.19.1/moment.min.js"></script> 

Moment.js is very interesting to play . Moment.js的玩法非常有趣。

let deviceTimestamp = 1531564520188828
var date = moment(deviceTimestamp/1000).format('dddd, MMMM Do, YYYY h:mm:ss A');

If you are looking to learn in detail about Moment.js , open https://momentjs.com/ : right click then click on inspect and try all type of possibilities in console. 如果您想了解有关Moment.js的详细信息,请打开https://momentjs.com/ :右键单击然后单击“检查”,然后尝试在控制台中尝试所有类型的可能性。

点击此处查看控制台结果

function removeLast6(str) {
   str = str.toString();
   str = str.slice(0, -6);
   str = parseInt(str);
   return str;
}

function convertToHumanDate(timestamp) {
   return moment.unix(timestamp).format('dddd, MMMM Do, YYYY h:mm:ss A');
}

const timestampNumber = await removeLast6(1531564520188828);

const date = await convertToHumanDate(timestampNumber);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM