Day Calculation is wrong - javascript

I'm making a clock, that calculates the number of days based on the date that the user input.
Let's say the user input November 20, 2020.
However, the calculate was really off, especially, if I put today date (Jan 06, 2021), then calculate started with -6.
Please take a look and let me know where I went wrong with the calculation.
This is my javascript for it:
document.addEventListener('DOMContentLoaded', function() {
// console.log("js running");
var days = document.querySelector('.days span');
var hour = document.querySelector('.hour');
var min = document.querySelector('.min');
var second = document.querySelector('.second');
var startDate = new Date(2020, 11, 20);
days.innerText = Math.floor((new Date - startDate)/86400000);
countTime();
function countTime() {
let today = new Date();
let ms = (today - startDate) % 86400000;
hour.innerText = Math.floor(ms / 3600000);
min.innerText = Math.floor(ms % 3600000 / 60000);
second.innerText = Math.floor(ms % 3600000 % 60000 / 1000);
}
setInterval(countTime, 1000);
}, false);

In your example, the ms variable was the number of days, and you used it in every other calculation, instead of the actual time difference. You can convert the difference to seconds, and work from there:
document.addEventListener('DOMContentLoaded', function() {
const $ = document.querySelector.bind(document),
days = $('.days span'),
hour = $('.hour'),
min = $('.min'),
second = $('.second');
const startDate = new Date(2020, 11, 20);
countTime();
function countTime() {
const today = new Date(),
diffInSeconds = Math.floor((today - startDate) / 1000);
days.innerText = Math.floor(diffInSeconds / 86400);
hour.innerText = Math.floor(diffInSeconds % 86400 / 3600);
min.innerText = Math.floor(diffInSeconds % 3600 / 60);
second.innerText = Math.floor(diffInSeconds % 60);
}
setInterval(countTime, 1000);
});
<span class="days"><span></span></span> days
<span class="hour"></span> hours
<span class="min"></span> minutes
<span class="second"></span> seconds

Related

Where am I going wrong with my math here to try and extract the correct hours from a date time?

I have a countdown timer and for some reason I can not get the hours to display correctly. No matter what, the hours is always shown as zero. Can someone double check my math to see where I am going wrong?
let countTitle = '';
let countDate = '';
let countDateValue = new Date();
const second = 1000;
const minute = second * 60;
const hour = minute * 60;
const day = hour * 24;
const today = new Date().toISOString().split("T")[0];
function countdown() {
const todayValue = new Date().getTime();
const difference = countDateValue - todayValue;
const days = Math.floor(difference / day);
const hours = Math.floor((difference % day) / hour);
const minutes = Math.floor((difference % hour) / minute);
const seconds = Math.floor((difference % minute) / second);
}
function getData(e) {
e.preventDefault();
countTitle = e.srcElement[0].value;
countValue = e.srcElement[1].value;
countDateValue = new Date(countValue).getTime();
countdown();
}
I don't see any issue with your code, it gives me perfect results unless input dates itself is wrong.
When I ran your code thorough some sample dates(1619628379441, 1619227379441), it results me perfectly 4 15 23 20.
let countTitle = '';
let countDate = '';
let countDateValue = new Date();
const second = 1000;
const minute = second * 60;
const hour = minute * 60;
const day = hour * 24;
const today = new Date().toISOString().split("T")[0];
function countdown() {
const todayValue = 1619227379441; //new Date().getTime();
const difference = countDateValue - todayValue;
const days = Math.floor(difference / day);
const hours = Math.floor((difference % day) / hour);
const minutes = Math.floor((difference % hour) / minute);
const seconds = Math.floor((difference % minute) / second);
console.log(days, hours, minutes, seconds)
}
function getData(e) {
countDateValue = 1619628379441; // new Date(countValue).getTime();
countdown();
}
getData();

javascript - get the date of next day in week?

how do I get, for example, the date of next monday and the time 5:30PM, and calculate the difference between current date and time and that date and time?
if I run it now at 8/28/2020 17:35, it should give me 8/31/2020 17:30 and the difference 2 days 23 hours 55 minutes.
I hope this help:
// takes dayIndex from Sunday(0) to Saturday(6)
const getNextDay = (dayIndex) => {
const today = new Date();
today.setDate(
today.getDate() + ((dayIndex - 1 - today.getDay() + 7) % 7) + 1
);
today.setHours(17, 30, 00);
return today;
};
const getTimeleft = (dateNow, dateFuture) => {
let seconds = Math.floor((dateFuture - dateNow) / 1000);
let minutes = Math.floor(seconds / 60);
let hours = Math.floor(minutes / 60);
let days = Math.floor(hours / 24);
hours = hours - days * 24;
minutes = minutes - days * 24 * 60 - hours * 60;
seconds = seconds - days * 24 * 60 * 60 - hours * 60 * 60 - minutes * 60;
return `${days} days ${hours} hours ${minutes} minutes`;
};
const now = new Date();
const nextMonday = getNextDay(1);
const timeleft = getTimeleft(now, nextMonday);
console.log(nextMonday.toLocaleString());
console.log(timeleft);
You could use moment.js, it's a very useful library when it comes to dates:
<script src="https://momentjs.com/downloads/moment.js"></script>
<script>
const today = moment();
const nextMonday = moment().add(1, 'weeks').isoWeekday(1);
nextMonday.set({'hour': 17, 'minute': 30, 'seconds': 0});
console.log(nextMonday.toString());
const duration = moment.duration(nextMonday.diff(today));
const days = duration.asDays();
const hours = (days - Math.floor(days)) * 24;
const minutes = (hours - Math.floor(hours)) * 60;
console.log("days", Math.floor(days));
console.log("hours", Math.floor(hours));
console.log("minutes", Math.floor(minutes));
</script>
Here is the working example:
function nextWeekMonday(date)
{
var diff = date.getDate() - date.getDay() + (date.getDay() === 0 ? -6 : 1);
var currWeekMonday = new Date(date.setDate(diff));
return new Date(currWeekMonday.getTime() + 7 * 24 * 60 * 60 * 1000);
}
function getDateDifference(current, future) {
// get total seconds between the times
var delta = Math.abs(future - current) / 1000;
// calculate (and subtract) whole days
var days = Math.floor(delta / 86400);
delta -= days * 86400;
// calculate (and subtract) whole hours
var hours = Math.floor(delta / 3600) % 24;
delta -= hours * 3600;
// calculate (and subtract) whole minutes
var minutes = Math.floor(delta / 60) % 60;
delta -= minutes * 60;
// what's left is seconds
var seconds = delta % 60;
return `${days} Days, ${hours} Hours, ${minutes} Minutes, ${seconds} Seconds`;
}
var curr = new Date; // get current date
var nextMonday = nextWeekMonday(curr);
console.log(getDateDifference(curr, nextMonday));

How can I calculate the difference between two times that are in 24 hour format which are in different dates?

In JavaScript, how can I calculate the difference between two times that are in 24 hour format which are having different dates?
Example:
Date1 is 2019/12/31 11:00:06 AM
Date2 is 2020/01/01 01:10:07 PM.
Time difference should be 02:10:13 in hh:MM:ss format
..how can get like this when date changes in appscript
Just use the Date
const dateDiffMs = (date1,date2 ) => {
const d1 = new Date(date1);
const d2 = new Date(date2);
return d1.getTime() - d2.getTime()
}
const ms2hms = (ms) => {
const sec = Math.floor(ms / 1000)
const min = Math.floor(sec / 60)
const h = Math.floor(min / 60)
return [
h,
min % 60,
sec % 60,
];
};
const format = (n) => n < 10 ? '0' + n : n;
const hms2str = ([h, min, sec]) => {
return `${h}:${format(min)}:${format(sec)}`
}
alert(hms2str(ms2hms(dateDiffMs('2020/01/01 01:10:07 PM', '2019/12/31 11:00:06 AM')))); // 26:10:01
This code works correctly if both date1 and date2 are in the same timezone. But i would recommend you to use moment.js or some other library
I would do this by gathering the date in second since whenever computers decided to keep track of time for us sometime in the 70's (epoch). Then pass it the second value and subtract, leaving the difference.
You would then need to convert it back to a date format I presume:
(function(){
var dateOneSeconds = new Date().getTime() / 1000;
setTimeout(function(){
var dateTwoSeconds = new Date().getTime() / 1000;
var seconds = dateTwoSeconds - dateOneSeconds;
console.log(seconds);
var timeDifferenceInDate = new Date(seconds * 1000).toISOString().substr(11, 8);
console.log(timeDifferenceInDate);
}, 3000);
})();
NOTE: I have used a timeout function - you will already have two dates that do not match to pop in.
EDIT: having been notified the days will not be calculated, you could maybe use date to calculate your time in seconds then use Math to create your display:
(function(){
var dateOneSeconds = new Date().getTime() / 1000;
setTimeout(function(){
var dateTwoSeconds = new Date().getTime() / 1000;
var seconds = dateTwoSeconds - dateOneSeconds;
console.log(seconds);
/* var timeDifferenceInDate = new Date(seconds * 1000).toISOString().substr(11, 8); */
seconds = Number(seconds);
var d = Math.floor(seconds / (3600*24));
var h = Math.floor(seconds % (3600*24) / 3600);
var m = Math.floor(seconds % 3600 / 60);
var s = Math.floor(seconds % 60);
timeDifferenceInDate = d + ':' + h + ':' + m + ':' + s;
console.log(timeDifferenceInDate);
}, 3000);
})();

What is the best way to get time backwards in Angular

What is the best way to get time for recent notifications (relative to current time) in an application, which are 5 sec ago, 10 sec ago or 7 hr 32 min ago?
In other words, I have a Date Object (in format 2019-03-12T10:05:32.257) which is for example 3 hr 6 min 9 sec ago from current time, I am wondering if there is a clean way to achieve the magic numbers 3, 6, 9 and display in html.
More cleaner way and generic implementation that I see to approach this problem could be.
Get the difference of date object in seconds converted as a first step
Then check for whether it could be fit into
years(divide by 31536000)
months(divide by 2592000)
days(divide by 86400)
hours(divide by 3600)
minutes(divide by 60)
function timesAgo(date) {
var seconds = Math.floor((new Date() - date) / 1000); // get the diffrence of date object sent with current date time of the system time
var interval = Math.floor(seconds / 31536000); // divide seconds by seconds in avg for a year to get years
//conditioning based on years derived above
if (interval > 1) {
return interval + " years";
}
interval = Math.floor(seconds / 2592000); // months check similar to years
if (interval > 1) {
return interval + " months";
}
interval = Math.floor(seconds / 86400); // days check similar to above
if (interval > 1) {
return interval + " days";
}
interval = Math.floor(seconds / 3600); // hours check
if (interval > 1) {
return interval + " hours";
}
interval = Math.floor(seconds / 60); // minutes check
if (interval > 1) {
return interval + " minutes";
}
return Math.floor(seconds) + " seconds"; // seconds check at the end
}
var withYears = new Date('August 19, 1999 23:15:30');
var withMonths = new Date('March 19, 2019 23:15:30');
var withDays = new Date('May 1, 2019 23:15:30');
var withPreviousDay = new Date('May 5, 2019 23:15:30');
var withHours = new Date('May 6, 2019 10:15:30');
console.log(timesAgo(withYears));
console.log(timesAgo(withMonths));
console.log(timesAgo(withDays));
console.log(timesAgo(withPreviousDay));
console.log(timesAgo(withHours));
Easier way If your using Angular and Moment is to use fromNow() function - Link
console.log(moment([2007, 0, 29]).fromNow(true)); // 12 years
console.log(moment([2007, 0, 29]).fromNow()); // 12 years ago
<script data-require="moment.js#*" data-semver="2.18.0" src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.0/moment.min.js"></script>
If you need an Angular Pipe check this times-ago-pipe
I guess you are trying to find the difference between two Date objects.
First, you can convert them to Date objects, followed by using getTime() to get it in milliseconds. After which, you subtract both date objects to get the time difference, and then divide it by 1000 to get the results in seconds.
const targetDate = new Date('2019-03-12T10:05:32.257').getTime();
const current = new Date().getTime();
const differenceInSeconds = (current - targetDate) / 1000;
From there, you can convert it to your required format (hours, minutes, and seconds).
And in order to convert them into hours, minutes and seconds,
const hours = Math.floor(differenceInSeconds / 3600);
const minutes = Math.floor(differenceInSeconds % 3600 / 60);
const seconds = Math.floor(differenceInSeconds % 3600 % 60);
This is how the end result will be like:
const targetDate = new Date('2019-03-12T10:05:32.257').getTime();
const current = new Date().getTime();
const differenceInSeconds = (current - targetDate) / 1000;
const hours = Math.floor(differenceInSeconds / 3600);
const minutes = Math.floor(differenceInSeconds % 3600 / 60);
const seconds = Math.floor(differenceInSeconds % 3600 % 60);
const result = `${hours} hr ${minutes} min ${seconds} sec`
console.log(result);

jQuery Timer Days/Months/Years

I'm creating a countdown Timer that counts down to a date that is inputted in the code for example April 6th 2016.
So far I have got it to output the amount of days, but I cannot figure out how to do the amount of months and years. I do not need Hours Minutes or seconds!
code in app.js
$(document).ready(function(){
eventTime = '6 April 2016';
})
Code in countdown.js:
(function($){
$.fn.countdown = function(options) {
var settings = { date: null };
if (options) {
$.extend(settings, options);
}
this_sel = $(this);
function count_exec () {
eventDate = Date.parse(settings['date']) / 1000;
currentDate = Math.floor($.now () / 1000);
seconds = eventDate - currentDate
days = Math.floor(seconds / (60 * 60 * 24));
months = Math.floor(seconds / (60 * 60 * 12));
alert(days);
}
count_exec();
}
})(jQuery);
Given two dates, use the following code to compute their difference in milliseconds, then in seconds, minutes, hours, days and months:
var currentDate = new Date();
var eventDate = new Date(2016, 3, 6); // months start from 0
var milliseconds = eventDate.getTime() - currentDate.getTime();
var seconds = parseInt(milliseconds / 1000);
var minutes = parseInt(seconds / 60);
var hours = parseInt(minutes / 60);
var days = parseInt(hours / 24);
var months = parseInt(days / 30);
seconds -= minutes * 60;
minutes -= hours * 60;
hours -= days * 24;
days -= months * 30;
For a more accurate difference in months, take a look at Difference in Months between two dates in JavaScript.

Categories

Resources