最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Convert integer to Date in node.js - Stack Overflow

programmeradmin2浏览0评论

I'm trying to convert a integer to a Date using node .js, and 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 ,

Example date: 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. But you never know.

I'm trying to convert a integer to a Date using node .js, and 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,

Example date: 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. But you never know.

Share Improve this question edited Feb 12, 2017 at 4:19 toastrackengima 8,7224 gold badges53 silver badges62 bronze badges asked Feb 12, 2017 at 3:17 Ben SpencerBen Spencer 1531 gold badge2 silver badges9 bronze badges 1
  • could you please include the whole (relevant) code. Especially the part that determines what exactly elodata is in your code. My guts somehow tell me that your elodata references the whole array. – Thomas Commented Feb 12, 2017 at 3:49
Add a comment  | 

2 Answers 2

Reset to default 13

You can pass in your value directly to a Date constructor in Javascript if it is an integer (which it appears to be in :

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 :

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. The result of that is implementation dependent but if 1461110400000 is a string it will almost certainly give an invalid date.

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.

发布评论

评论列表(0)

  1. 暂无评论