I am trying to code a count down timer in Vanilla Javascript. Below is the code:-
var futureDate = new Date("oct 31,2021 10:00:00").getTime();
var currentDate = new Date().getTime();
var diffTime = futureDate - currentDate;
console.log(diffTime);
var days = Math.floor(diffTime / (1000* 24* 60*60));
console.log(days);
var hours = Math.floor(diffTime / (1000 * 60 * 60));
console.log(hours);
var minutes = Math.floor(diffTime / (1000 * 60));
console.log(minutes);
var seconds = Math.floor(diffTime / (1000));
console.log(seconds);
Below is the output of the code provided in the console.
This output is in accordance with below image
But I am failing to understand the particular code written in w3schools as highlighted in blue color in the image below
I am not able to figure out the difference between 2 code written?
Date.getTime() returns the number of milliseconds since the Unix epoch (1900-01-01 00:00:00).
When you subtract the time between 2 dates, you will get the time difference in milliseconds. In your code, you are showing
The total number of hours between the dates
The total number of minutes between the dates
The total number of seconds between the dates
Let's take the number of hours as an example, the code written in w3schools takes the remainder from dividing the time difference by the number of milliseconds per day. This way, you will get the time difference in less than 24 hours and you can use it to calculate the time difference in hours.
Do the same for the minutes and seconds and you will get the same result written in w3schools
var futureDate = new Date( "oct 31,2021 10:00:00" ).getTime();
var currentDate = new Date().getTime();
var timeDiffInMilliseconds = futureDate - currentDate;
var millisecondsPerSecond = 1000;
var millisecondsPerMinute = millisecondsPerSecond * 60; // 1000 * 60
var millisecondsPerHour = millisecondsPerMinute * 60; // 1000 * 60 * 60
var millisecondsPerDay = millisecondsPerHour * 24; // 1000 * 60 * 60 * 24
console.log( 'timeDiffInMilliseconds: ' + timeDiffInMilliseconds );
var days = Math.floor( timeDiffInMilliseconds / millisecondsPerDay );
console.log( 'days: ' + days );
var timeDiffInLessThan1Day = timeDiffInMilliseconds % millisecondsPerDay;
var hours = Math.floor( timeDiffInLessThan1Day / millisecondsPerHour );
console.log( 'hours: ' + hours );
var timeDiffInLessThan1Hour = timeDiffInMilliseconds % millisecondsPerHour;
var minutes = Math.floor( timeDiffInLessThan1Hour / millisecondsPerMinute );
console.log( 'minutes: ' + minutes );
var timeDiffInLessThan1Minute = timeDiffInMilliseconds % millisecondsPerMinute;
var seconds = Math.floor( timeDiffInLessThan1Minute / millisecondsPerSecond );
console.log( 'seconds: ' + seconds );
Okay, first you need to understand the basic concept of dates in vanilla javascript.
1 second = 1000 milliseconds
1 minute = 60 seconds
1 hour = 60 minutes
1 day = 24 hours
Math.floor is simply used for returning the highest rounded value possible.
Now coming to your question,
var distance = countDownDate - now;
This line basically takes two UNIX format date integers and gives you the difference in the form of unix timestamp. So once you get the difference you need to find out how many hours, minutes and days it comprises of, and that's just it.
We use the simple formulas I mentioned to top to identify just that.
1000 * 60 * 60 * 24 is 1 day
So we divide the total difference in two dates by the 1 day to get the number of days in total with the following line:
var days = Math.floor(distance / (1000 * 60 * 60 * 24));
Similarly, with the code below, we take the difference in two dates and first get the number of days from it and then whatever time remains we use that time to further calculate the hours by dividing the value by (1000 * 60 * 60).
var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
The following line first calculates the number of hours from the difference and then whatever remains is then further divided by a minute to get the totals minutes remaining. Similarly, concept will be applied to calculate the seconds.
var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
(function timeAgo(selector) {
console.clear();
var dt1 = new Date("2019-12-17 13:12:34");
var dt2 = new Date();
var diff = (dt2.getTime() - dt1.getTime());
var hours = Math.floor(diff / (1000 * 60 * 60));
diff -= hours * (1000 * 60 * 60);
var mins = Math.floor(diff / (1000 * 60));
diff -= mins * (1000 * 60);
document.getElementById("demo").innerHTML = mins + 'minutes ago';
setTimeout(timeAgo, 60000);
})();
<span id="demo" />
Use moment.js.
moment("20111031", "YYYYMMDD").fromNow()
// 8 years ago
moment.js is great, you can use that but in case you are looking for a pure JS solution:
(function getTimeDiff() {
let datetime = new Date("2016-04-18 01:07:23.132446").getTime();
let now = new Date().getTime();
let milisecDiff = (datetime < now) ? now - datetime : datetime - now;
let days = Math.floor(milisecDiff / 1000 / 60 / (60 * 24));
let dateDiff = new Date(milisecDiff);
console.log(`${days} Days ${dateDiff.getHours()} Hours ${dateDiff.getMinutes()} Minutes ${dateDiff.getSeconds()} Seconds`);
})();
You can further format the output to serve your use cases.
I read many questions here but not find a solution for problem.
I have one page which has two dates and one text box. When I click on text box the difference of two dates in days will show on text box. But when I change the dates and click on text box it doesn't work.
Code
$('#totalNoOfLeave').click(function(){
var date1 = new Date($('#leaveStartDate').getValue());
var date2 = new Date($('#leaveEndingDate').getValue());
var timeDiff = Math.abs(date2.getTime() - date1.getTime());
var diffDays = Math.ceil(timeDiff / (1000 * 3600 * 24));
$('#totalNoOfLeave').setValue(diffDays);
});
Please help.
Use this :
$('body').on('click', '#totalNoOfLeave', function () {
var date1 = new Date($('#leaveStartDate').getValue());
var date2 = new Date($('#leaveEndingDate').getValue());
var timeDiff = Math.abs(date2.getTime() - date1.getTime());
var diffDays = Math.ceil(timeDiff / (1000 * 3600 * 24));
$('#totalNoOfLeave').setValue(diffDays);
});
I have a JavaScript Date() object and I only need the milliseconds of the current time; I don't want any dates.
var myDate = new Date();
// get millis only for time and not for date
Is there a possibility to do this?
All you need to do is:
var millis = myDate.getMilliseconds();
You could use the remainder of a day length of the epoc.
var d = +(new Date());
console.log(d);
d = d % (1000 * 60 * 60 * 24);
console.log(d);
console.log('h', d / (1000 * 60 * 60) | 0);
console.log('m', (d % (1000 * 60 * 60)) / (1000 * 60) | 0);
console.log('s', (d % (1000 * 60)) / 1000 | 0);
If I understand correctly you want the ms that have elapsed in the day current day?
You could try something like
var now = new Date().getTime();
var startOfDay = new Date().setHours(0,0,0,0);
var ms = now - startOfDay;
console.log(now);
console.log(startOfDay);
console.log(ms);
Sure is.
Step 1: Declare a variable as a date.
var today = new Date();
Step 2: Redefine variable with .getHours() method.
today = today.getHours();
Step 3: Divider by milliseconds in a day.
today = today / 86400000;
function getMs() {
var d = new Date();
var n = d.getMilliseconds();
document.getElementById("setMs").innerHTML = n;
}
<button onclick="getMs()">Click me</button>
<p id="setMs"></p>
Hope it helps.
var date1 = new Date("04.11.2016");
var date2 = new Date("19.11.2016");
var timeDiff = Math.abs(date2.getTime() - date1.getTime());
var diffDays = Math.ceil(timeDiff / (1000 * 3600 * 24));
alert(diffDays);
Trying get different between those Dates, but my date format is that "04.11.2016", Result show NaN
var date1 = new Date("11/04/2016");
var date2 = new Date("11/19/2016");
var timeDiff = Math.abs(date2.getTime() - date1.getTime());
var diffDays = Math.ceil(timeDiff / (1000 * 3600 * 24));
alert(diffDays);
change the format of date.
it should be MM/DD/YYYY
Hope this helps.
The easiest way is to use moment.js library:
var date1 = moment('04.11.2016', 'MM.DD.YYYY'),
date2 = moment('19.11.2016', 'MM.DD.YYYY'),
diffDays = date2.diff(date1, 'days'); // you can wrap it in Math.abs()
The ugly js way:
var input1 = '04.11.2016',
parts1 = input1.split('.'),
date1 = new Date(parts1[2], parts1[1], parts1[0]),
input2 = '19.11.2016',
parts2 = input2.split('.'),
date2 = new Date(parts2[2], parts2[1], parts2[0]),
timeDiff = Math.abs(date2.getTime() - date1.getTime()),
diffDays = Math.ceil(timeDiff / (1000 * 3600 * 24));
Change the Month and Date order First should be month then date... MM/DD/YYYY
var date1 = new Date("11.04.2016");
var date2 = new Date("11.19.2016");
var timeDiff = Math.abs(date2.getTime() - date1.getTime());
var diffDays = Math.ceil(timeDiff / (1000 * 3600 * 24));
alert(diffDays);
Your second date is incorrect. Parser is considering this format MM.DD.YYY and you have supplied out of range month.
var date1 = new Date("04.11.2016");
var date2 = new Date("09.11.2016");
var timeDiff = Math.abs(date2.getTime() - date1.getTime());
var diffDays = Math.ceil(timeDiff / (1000 * 3600 * 24));
alert(diffDays);
A date consists of a year, a month, a day, an hour, a minute, a second, and milliseconds.
Date objects are created with the new Date() constructor.
There are 4 ways of initiating a date:
new Date()
new Date(milliseconds)
new Date(dateString)
new Date(year, month, day, hours, minutes, seconds, milliseconds)
so you can split them and then use it
Just change the first two lines as below
var date1 = new Date(2016,11,4);
var date2 = new Date(2016,11,19);
new date("mm dd yyyy") format was wrong
(function () {
var date1 = new Date("11 04 2016");
var date2 = new Date("11 19 2016");
var timeDiff = Math.abs(date2.getTime() - date1.getTime());
var diffDays = Math.ceil(timeDiff / (1000 * 3600 * 24));
console.log(diffDays);
})()
JS expects date to in MM-DD-YYYY and not DD-MM-YYYY. Ideal way would be to use moment.js, but you can use something like this:
function createCustomDate(dateString){
var dateArr = dateString.split(/[^0-9]/).reverse().join("-")
return new Date(dateArr);
}
var dateStr1 = "04.11.2016";
var dateStr2 = "19.11.2016";
var date1 = createCustomDate(dateStr1);
var date2 = createCustomDate(dateStr2);
var timeDiff = Math.abs(date2.getTime() - date1.getTime());
var diffDays = Math.ceil(timeDiff / (1000 * 3600 * 24));
console.log(diffDays);
new Date("19.11.2016");
this is Invalid Date. So, difference is be NaN .
change the format to mm/dd/yyyy and it will work.
You can use moment.js,
d = moment('11.16.2016') // here date format was in "MM.DD.YYYY"
e = moment('11.04.2016') // here date format was in "MM.DD.YYYY"
getDiffbydays = e.diff(d,'days') // get diff by days you can use day
getDiffbyyears = e.diff(d,'year') // get diff by years you can use year
getDiffbymonth = e.diff(d,'month') // get diff by months you can use month
Check this solution which uses a function called getDate to convert the date string of the format "04.11.2016" to a JavaScript Date object.
function getDate(dateStr) {
var arr = dateStr.split('.');
return new Date(arr[2], arr[1], arr[0]);
}
var start = getDate("04.11.2016");
var end = getDate("19.11.2016");
var timeDiff = Math.abs(end.getTime() - start.getTime());
var diffDays = Math.ceil(timeDiff / (1000 * 60 * 60 * 24))
console.log('Number of days: ' + diffDays);
In order to use this code to create a Custom JavaScript Variable in Google Tag Manager, you can modify the above code or the one which you choose to be inside a function - reference.