'Converting string time into milliseconds
I have a set of individual json data, they each have a time stamp for when it was created in this exact format e.g.
[ {"Name": "Jake", "created":"2013-03-01T19:54:24Z" },
{"Name": "Rock", "created":"2012-03-01T19:54:24Z" } ]
As a result I wish to use 'created' within a function which calculates that if the data was entered 60days or less from today it will appear in italic. However, the function I've attempted has no effect. I'm attempting to do the calculation in milliseconds:
node.append("text")
.text(function(d) { return d.Name; })
.style("font", function (d)
{ var date = new Date(d.created);
var k = date.getMilliseconds;
var time = new Date ();
var n = time.getTime();
if(k > (n - 5184000) ) {return " Arial 11px italic"; }
else { return " Arial 11px " ; }
})
I am curious whether I am actually converting the data at all into milliseconds. Also, if I am getting todays date in milliseconds.
Thanks in advance
EDIT: Example - http://jsfiddle.net/xwZjN/84/
Solution 1:[1]
To get the milliseconds since epoch for a date-string like yours, use Date.parse():
// ...
var k = Date.parse( d.created );
// ...
Solution 2:[2]
let t = "08:30"; // hh:mm
let ms = Number(t.split(':')[0]) * 60 * 60 * 1000 + Number(t.split(':')[1]) * 60 * 1000;
console.log(ms);
let t = "08:30"; // mm:ss
let ms = Number(t.split(':')[0]) * 60 * 1000 + Number(t.split(':')[1]) * 1000;
console.log(ms);
Solution 3:[3]
If you string is in the form of mm:ss, Follow the procedure and resolve,
var t = "08:00";
var r = Number(t.split(':')[0])*60+Number(t.split(':')[1])*1000;
console.log(r)
Solution 4:[4]
var timeInString = "99:99:99:99"; // Any value here
var milliseconds;
if (timeInString.split(":").length === 2) {
/* For MM:SS */
milliseconds =
Number(timeInString.split(":")[0]) * 60000 +
Number(timeInString.split(":")[1]) * 1000;
} else if (timeInString.split(":").length === 3) {
/* For HH:MM:SS */
milliseconds =
Number(timeInString.split(":")[0]) * 3600000 +
Number(timeInString.split(":")[1]) * 60000 +
Number(timeInString.split(":")[2]) * 1000;
} else if (timeInString.split(":").length === 4) {
/* For DD:HH:MM:SS */
milliseconds =
Number(timeInString.split(":")[0]) * 86400000 +
Number(timeInString.split(":")[1]) * 3600000 +
Number(timeInString.split(":")[2]) * 60000 +
Number(timeInString.split(":")[3]) * 1000;
}
console.log(`Milliseconds in ${timeInString} - ${milliseconds}`);
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | Ank |
| Solution 3 | |
| Solution 4 |
