Reputation: 177
I've specified a specific time on a certain day. Now I wish to calculate the milliseconds from the beginning of that specific day to the set time of that day? I was hoping to do that with below code, but instead it shows nothing? What am I doing wrong?
var now = new Date().getTime();
var oneday = 1000 * 60 * 60 * 24;
var countDownDate = new Date("January 10, 2018 00:01").getTime();
var countDownStart = new Date(countDownDate.getFullYear(), countDownDate.getMonth(), countDownDate.getDate(), 0, 0, 0, 0);
var countDownTime = countDownDate.getTime() - countDownStart.getTime();
var div = document.getElementById('result');
div.innerText = countDownTime;
I specify the countDownDate. Then I mark the beginning of that countDownDate into the variable countDownStart. Next I calculate the time passed since 00:00 of January 10 to 00:01 of January 10 by subtracting countDownStart from countDownDate. But no result is shown...
Upvotes: 0
Views: 77
Reputation: 21575
Your logic is fine here. The only issue is this line here:
var countDownDate = new Date("January 10, 2018 00:01").getTime();
Since you used .getTime()
the variable countDownDate
is no longer a date. As such in the following statementcountDownDate.getFullYear()
and forward isn't going to work. Simply remove .getTime()
and it will work as expected:
var now = new Date().getTime();
var oneday = 1000 * 60 * 60 * 24;
var countDownDate = new Date("January 10, 2018 00:01");
var countDownStart = new Date(countDownDate.getFullYear(), countDownDate.getMonth(), countDownDate.getDate(), 0, 0, 0, 0);
var countDownTime = countDownDate.getTime() - countDownStart.getTime();
console.log(countDownTime)
Upvotes: 0
Reputation: 23859
Your code has only one issue, and that is that you've assigned the result of .getTime()
to countDownDate
, which will be a number.
That's why JavaScript cannot call getFullYear
, or any other function on that number, because those will be invalid calls.
To correct that, just remove the .getTime()
, and it will work fine.
var now = new Date().getTime();
var oneday = 1000 * 60 * 60 * 24;
var countDownDate = new Date("January 10, 2018 00:01");
var countDownStart = new Date(countDownDate.getFullYear(), countDownDate.getMonth(), countDownDate.getDate(), 0, 0, 0, 0);
var countDownTime = countDownDate.getTime() - countDownStart.getTime();
var div = document.getElementById('result');
div.innerText = countDownTime;
<div id="result">
<div>
Upvotes: 2