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...
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>
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)
Related
Im trying to get the number of seconds between two dates in javascript.
Questions here and here suggest that a simple subtract operation should do the trick and other answers suggest that you use either the .getTime() or .valueOf() attributes.
But Despite all that when I subtract the two dates, Which are apart by 5 seconds I get the value 1551181475795 which is way too large to be correct.
Here is my code:
var countDownDate = new Date("Mar 16, 2019 16:33:25").valueOf();
var dist = 347155200;
// Update the count down every 1 second
var x = setInterval(function() {
// Get todays date and time
var now = new Date("Mar 16, 2019 16:33:30");
// Find the distance between now and the count down date
var distance = Math.abs(now - countDownDate / 1000);
// Display the result in the element with id="demo"
document.getElementById("demo").innerHTML = distance;
// If the count down is finished, write some text
if (distance < 0) {
clearInterval(x);
document.getElementById("demo").innerHTML = "EXPIRED";
}
}, 1000);
<p id='demo'>
As you can see both times are only apart by 5 seconds but the value that separates them makes no sense.
Thanks in Advance!
It's a matter of operations order, you're dividing the countDownDate by 1000 before doing the subtraction (you're calculating now - countDownDate / 1000 however, you should calculate (now - countDownDate) / 1000, subtraction first):
var countDownDate = new Date("Mar 16, 2019 16:33:25").valueOf();
var dist = 347155200;
// Update the count down every 1 second
var x = setInterval(function() {
// Get todays date and time
var now = new Date("Mar 16, 2019 16:33:30");
// Find the distance between now and the count down date
var distance = Math.abs((now - countDownDate) / 1000);
// Display the result in the element with id="demo"
document.getElementById("demo").innerHTML = distance;
// If the count down is finished, write some text
if (distance < 0) {
clearInterval(x);
document.getElementById("demo").innerHTML = "EXPIRED";
}
}, 1000);
<p id="demo"></p>
As you had researched you can simply reduce the newer date from the older one which returns the milliseconds between the two dates.
Dividing that with 1000 gives you the seconds.
let start = new Date("Mar 16, 2019 16:33:25")
let end = new Date("Mar 16, 2019 16:33:30");
let secondsBetween = (end - start) / 1000;
console.log("without value of:", secondsBetween, "seconds")
start = new Date("Mar 16, 2019 16:33:25").valueOf()
end = new Date("Mar 16, 2019 16:33:30").valueOf()
secondsBetween = (end - start) / 1000;
console.log("using value of:",(end - start) / 1000, "seconds")
I write the code below:
var _MS_PER_Day=24*60*60*1000;
var utc1 = Date.UTC(1900, 1, 1);
var utc2 = Date.UTC(2014,11,16);
var x = Math.ceil((utc2 - utc1) / _MS_PER_Day);
alert(x);
I want to calculate the date difference between the two dates.The actual date difference is 41957 but after running my code i get 41956 ,one date less.What is wrong with my code ?
Your code is calculating the difference between Feb 1, 1900 and Dec 16, 2014 (41956 days). The value month should be between 0...11 (where 0 is January). Correct the month numbers to get the expected result:
var _MS_PER_Day = 1000 * 60 * 60 * 24;
var utc1 = Date.UTC(1900, 0, 1); // Jan 01, 1900
var utc2 = Date.UTC(2014, 10, 16); // Nov 16, 2014
var x = Math.ceil((utc2 - utc1) / _MS_PER_Day);
alert(x); // 41957
This is an alternate code for the above which will give you 41957.
var date1 = new Date("1/1/1900");
var date2 = new Date("11/16/2014");
var timeDiff = Math.abs(date2.getTime() - date1.getTime());
var diffDays = Math.ceil(timeDiff / (1000 * 3600 * 24));
alert(diffDays);
Reference :
Get difference between 2 dates in javascript?
The months are from 0 to 11 considering 0 as January.
You may also use getTime method to get the UTC timestamp in miliseconds.
var _MS_PER_Day = 1000 * 60 * 60 * 24;
var t1 = new Date(1900, 0, 1); // Jan 01, 1900
var t2 = new Date(2014, 10, 16); // Nov 16, 2014
var tdiff = Math.ceil((t2.getTime() - t1.getTime()) / _MS_PER_Day); // tdiff = 41957
http://www.w3schools.com/jsref/jsref_gettime.asp
I think you can use http://momentjs.com/
it give you the best result.
const a = new Date(YOUR_START_TIME),
b = new Date()
let diff = moment([b.getFullYear(), b.getMonth(), b.getDate()])
.diff(moment([a.getFullYear(), a.getMonth(), a.getDate()]), 'years', true)
I am learning to use Date object in Javascript. Tried to calculate difference between now and some set date, but it returns a much larger value than inteded. The codepen is here, I can't seem to figure what I did wrong... Help?
var setdate = new Date(2014, 4, 27, 14,30); //27th of April this year at 14:30
var now = new Date(); //Now, whenever this code runs
var diff = Math.round((setdate.getTime() - now.getTime())/1000); //Difference in seconds
function NiceTimer(delta) { //Decompose the difference in seconds into date units.
this.days = Math.floor(delta/ 86400);
delta -= this.days*86400; //Subtract the value once it has been "extracted".
this.hours = Math.floor(delta/ 3600);
delta -= this.hours*3600;
this.minutes = Math.floor(delta/ 60);
delta -= this.minutes*60;
this.seconds = delta;
this.printString = function() {
return "The event starts in "+this.days+" days, "+this.hours+" hours, "+this.minutes+" minutes and "+this.seconds+" seconds"; //Output a readable countdown string
}
}
var timer = new NiceTimer(diff);
var el = document.getElementById("timer");
el.innerHTML = timer.printString();
var setdate = new Date(2014, 4, 27, 14,30); //27th of April this year at 14:30
Change the four to a three, months start at index zero.
var setdate = new Date(2014, 3, 27, 14,30);
Date # MDN:
month
Integer value representing the month, beginning with 0 for January to 11 for December.
I apologize if this question has been asked already but I couldn't find it for my problem.
I have seen this but am not sure what the number it returns represents: Date() * 1 * 10 * 1000
I'd like to set a future moment in time, and then compare it to the current instance of Date() to see which is greater. It could be a few seconds, a few minutes, a few hours or a few days in the future.
Here is the code that I have:
var futureMoment = new Date() * 1 *10 * 1000;
console.log('futureMoment = ' + futureMoment);
var currentMoment = new Date();
console.log('currentMoment = ' + currentMoment);
if ( currentMoment < futureMoment) {
console.log('currentMoment is less than futureMoment. item IS NOT expired yet');
}
else {
console.log('currentMoment is MORE than futureMoment. item IS expired');
}
Javascript date is based on the number of milliseconds since the Epoch (1 Jan 1970 00:00:00 UTC).
Therefore, to calculate a future date you add milliseconds.
var d = new Date();
var msecSinceEpoch = d.getTime(); // date now
var day = 24 * 60 * 60 * 1000; // 24hr * 60min * 60sec * 1000msec
var futureDate = new Date(msecSinceEpoc + day);
See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date
var futureMoment = new Date() * 1 *10 * 1000;
becomes
var now = new Date();
var futureMoment = new Date(now.getTime() + 1 *10 * 1000);
I think you mean to add time. Not multiply it.
If you deal with time, there is a lot of tools to choose.
Try moment library.
Used following code to compare selected date time with current date time
var dt = "Thu Feb 04 2016 13:20:02 GMT+0530 (India Standard Time)"; //this date format will receive from input type "date"..
function compareIsPastDate(dt) {
var currDtObj = new Date();
var currentTime = currDtObj.getTime();
var enterDtObj = new Date(dt);
var enteredTime = enterDtObj.getTime();
return (currentTime > enteredTime);
}
I need to be able to get the correct timezoneOffset by using javascript, if a user has disabled "Automatically adjust time clock for Daylights saving time" on his or her computer.
For example if i turn on automatically adjust DST i get -420 in june, and -480 in January for Pacific Time zone.
However if i disable Automatically adjust DST i get -480 for both January and June.
Is there any way to correct this behavior so that i get the expected DST even if automatically adjust DST time is checked off?
This is a function I've used a little while back (source), hope this helps.
function TimezoneDetect(){
var dtDate = new Date('1/1/' + (new Date()).getUTCFullYear());
var intOffset = 10000; //set initial offset high so it is adjusted on the first attempt
var intMonth;
var intHoursUtc;
var intHours;
var intDaysMultiplyBy;
//go through each month to find the lowest offset to account for DST
for (intMonth=0;intMonth < 12;intMonth++){
//go to the next month
dtDate.setUTCMonth(dtDate.getUTCMonth() + 1);
//To ignore daylight saving time look for the lowest offset.
//Since, during DST, the clock moves forward, it'll be a bigger number.
if (intOffset > (dtDate.getTimezoneOffset() * (-1))){
intOffset = (dtDate.getTimezoneOffset() * (-1));
}
}
return intOffset;
}
To detect DST without using getTimezoneOffset use this:
var rightNow = new Date();
var jan1 = new Date(rightNow.getFullYear(), 0, 1, 0, 0, 0, 0);
var temp = jan1.toGMTString();
var jan2 = new Date(temp.substring(0, temp.lastIndexOf(" ")-1));
var std_time_offset = (jan1 - jan2) / (1000 * 60 * 60);
var june1 = new Date(rightNow.getFullYear(), 6, 1, 0, 0, 0, 0);
temp = june1.toGMTString();
var june2 = new Date(temp.substring(0, temp.lastIndexOf(" ")-1));
var daylight_time_offset = (june1 - june2) / (1000 * 60 * 60);
var dst;
if (std_time_offset == daylight_time_offset) {
dst = "0"; // daylight savings time is NOT observed
} else {
dst = "1"; // daylight savings time is observed
}