简体   繁体   English

在node.js中将整数转换为Date

[英]Convert integer to Date in node.js

I'm trying to convert a integer to a Date using node .js, and Date. 我正在尝试使用节点.js和Date将整数转换为Date。

I know that this is a very common question but all the solutions that have been posted before have failed to help me. 我知道这是一个非常普遍的问题,但是之前发布的所有解决方案都无法帮助我。

I am getting the dates from a json file found at http://api.guardian.gg/chart/elo/4611686018432537994 , 我从http://api.guardian.gg/chart/elo/4611686018432537994上找到的json文件获取日期,

Example date: 1461110400000 日期示例:1461110400000

What I've tried: 我尝试过的

    var date = String(new Date(elodata.x));

and

    var date = String(new Date(parseInt(elodata.x)));

But I get invalid date as a result. 但结果是我得到了无效的日期。

I realise that this might not be doable because I don't know how guardian.gg handles this data. 我意识到这可能不可行,因为我不知道Guardian.gg如何处理这些数据。 But you never know. 但是你永远不知道。

You can pass in your value directly to a Date constructor in Javascript if it is an integer (which it appears to be in : 您可以将值直接传递给Javascript中的Date构造函数(如果它是整数(它似乎位于):

var date = new Date(elodata.x);

Likewise, you can also use the the setTime() function in Javascript to pass your integer value in if you already have an existing object : 同样,如果已有对象,也可以使用Javascript中的setTime()函数传递整数值:

var date = new Date();
d.setTime(elodata.x);

Example

 var d1 = new Date(1461110400000); console.log(`Constructor: ${d1}`); var d2 = new Date(); d2.setTime(1461110400000); console.log(`setTime(): ${d2}`); 

When a single argument is passed to the Date constructor, if it's a string it will be parsed. 当将单个参数传递给Date构造函数时,如果它是字符串,则将对其进行解析。 The result of that is implementation dependent but if 1461110400000 is a string it will almost certainly give an invalid date. 其结果取决于实现,但是如果1461110400000是字符串,则几乎可以肯定会给出一个无效的日期。

If given a number, it's treated as a time value. 如果提供数字,则将其视为时间值。 So if you're passing a number, make sure it's type number: 因此,如果要传递数字,请确保其为数字类型:

 var timeValue = '1461110400000'; console.log( new Date(+timeValue)); 

You could also use Number(timeValue) or parseInt(timeValue) but unary + is less to type. 您也可以使用Number(timeValue)parseInt(timeValue)但一元+键入较少。

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

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