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.
Related
I'm trying to display the countdown timer between an enddate/time column and the system date/time column using below code. It's not displaying the timer.
I have created a page item P3_TIMER and it has a column P3_STARTDATE.
var timer;
var endDate = new Date();
endDate.setDate(endDate.getDate()); //End date is the sys date
timer = setInterval(function() {
timeBetweenDates(endDate);
}, 1000);
function timeBetweenDates(toDate) {
var dateEntered = :P3_STARTDATE;
var now = new Date();
var difference = dateEntered.getTime() - now.getTime();
if (difference <= 0) {
// Timer done
clearInterval(timer);
} else {
var seconds = Math.floor(difference / 1000);
var minutes = Math.floor(seconds / 60);
var hours = Math.floor(minutes / 60);
var days = Math.floor(hours / 24);
hours %= 24;
minutes %= 60;
seconds %= 60;
$("#days").text(days);
$("#hours").text(hours);
$("#minutes").text(minutes);
$("#seconds").text(seconds);
}
$s('P3_TIMER',timer);
}
It's not possible to mix pl/sql and javascript. They're different languages and run in different environments.
function timeBetweenDates(toDate) {
var dateEntered = :P3_STARTDATE; >>> This is pl/sql
var now = new Date();
The P3_STARTDATE needs to be converted to a javascript date object. That cannot be directly, some parsing is needed as shown in this thread.
For the example below the assumption is made that the date is passed in format DD-MON-YYYY.
var timer;
var endDate = new Date();
endDate.setDate(endDate.getDate()); //End date is the sys date
timer = setInterval(function() {
timeBetweenDates(endDate);
}, 1000);
function parseDate(s) {
var months = {jan:0,feb:1,mar:2,apr:3,may:4,jun:5,
jul:6,aug:7,sep:8,oct:9,nov:10,dec:11};
var p = s.split('-');
return new Date(p[2], months[p[1].toLowerCase()], p[0]);
}
function timeBetweenDates(toDate) {
var dateEntered = parseDate(apex.item( "P63_DATE" ).getValue() );
var now = new Date();
var difference = dateEntered.getTime() - now.getTime();
if (difference <= 0) {
// Timer done
clearInterval(timer);
} else {
var seconds = Math.floor(difference / 1000);
var minutes = Math.floor(seconds / 60);
var hours = Math.floor(minutes / 60);
var days = Math.floor(hours / 24);
hours %= 24;
minutes %= 60;
seconds %= 60;
$("#days").text(days);
$("#hours").text(hours);
$("#minutes").text(minutes);
$("#seconds").text(seconds);
}
apex.item("P63_TIMER").setValue(`Days: ${days}, Hours: ${hours}, Minutes: ${minutes}, Seconds: ${seconds}`);
}
I have ecommerce website. In that for same day delivery need to order before 11. So before 30 minutes of the end time(i.e. 11) i want to show that timer section.
Below code I am trying But getting issue how to set timer functionality.
setInterval(function(){
var secs = 1800;
var date = new Date;
// date.setTime(result_from_Date_getTime);
var seconds = date.getSeconds();
var minutes = date.getMinutes();
var hour = date.getHours();
console.log("Hour"+hour+"Minutes"+minutes+"seconds"+seconds);
// console.log(minutes);
// console.log(seconds);
if(hour == 10 && minutes>=30)
{
var mins = secs / 60;
console.log("Timer"+mins);
$('.top-header-content1').removeClass('hide-ticker1');
}
else if (hour >= 11){
console.log("hii11");
$('.top-header-content1').addClass('hide-ticker1');
}
secs--;
},1000);
If anyone have a idea , how to add time please let me know
Hi you use this code below:
/// the counting date
var countDownDate = new Date("Jan 5, 2024 15:37:25").getTime();
// Update the count down every 1 second
var x = setInterval(function() {
// Get today's date and time
var now = new Date().getTime();
// Find the distance between now and the count down date
var distance = countDownDate - now;
// Time calculations for days, hours, minutes and seconds
var days = Math.floor(distance / (1000 * 60 * 60 * 24));
var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
var seconds = Math.floor((distance % (1000 * 60)) / 1000);
// Display the result in the element with id="demo"
document.getElementById("demo").innerHTML = days + "d " + hours + "h "
+ minutes + "m " + seconds + "s ";
// If the count down is finished
if (distance < 0) {
clearInterval(x);
document.getElementById("demo").innerHTML = "EXPIRED";
}
}, 1000);
<p id="demo"></p>
The following code will start a setInterval() in which during a time window between 10:30h and 11:00h a countdown will be shown. Before 10:30h and after 11:00h different messages are shown. And after 11:00h the setInterval is cleared.
// div for output on page:
const demo=document.getElementById("demo"),
// today's date
today = new Date();
today.setHours(11);today.setMinutes(0);today.setSeconds(0);
today.intv=setInterval(checkTime,1000);
function checkTime(){
const now=new Date();
if (now>today) {
demo.textContent="Order today for tomorrow's delivery.";
clearInterval(today.intv);
}
else if (now>(today-1800000)){
let tsec=Math.floor((today-now)/1000),
sec=tsec%60,
min=(tsec-sec)/60;
demo.textContent=`${min} minutes and ${sec} seconds left if you want to order for today's delivery.`;
} else
demo.textContent="Order now for today's delivery!"
}
<p id="demo"></p>
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
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));
I am building an Instagram feed with JQuery into my site and want to show how long has passed since the post was submitted in a short form like: 23H or 2D or 3M or 1Y depending on how long its been. I've got my two date objects but I can't figure our how to calculate the difference and display it how i want.
I am fairly new to JS/Jquery and as far as i could get was:
var pd = new Date(postDate);
var nd = new Date();
var nd = nd.getTime();
var difference = nd-pd;
How do I calculate the difference between two dates in hours, days, months and years?
Thanks.
Doing anything with dates is generally painful.
If you aren't committed to using that exact format, you can use a library for this instead.
moment.js has a .fromnow() function.
or timeago.js can be used to update the element on the page periodically, so if the user leaves the page open for a few minutes, the time stamps will count up.
You can do this to get the time elapsed since posted
var timeDiff = Math.abs(nd.getTime() - pd.getTime());
var diffDays = Math.ceil(timeDiff / (1000 * 3600 * 24));
you can try like this.
var pd = new Date(postDate);
var nd = new Date();
var Hours = nd.getHours() - pd.getHours();
var Days = nd.getDay() - pd.getDay();
var Months = nd.getMonth() - pd.getMonth();
var Years = nd.getYear() - pd.getYear();
or get millisecods diference
var miliseconds = (nd - pd).getTime(); //gets time in miliseconds since 1/1/1970
then use your logic to calculate hours, days, months and years
you can have a look at this Work with a time span in Javascript
moments
ar date1 = new Date("7/Nov/2012 20:30:00");
var date2 = new Date("20/Nov/2012 19:15:00");
var diff = date2.getTime() - date1.getTime();
var days = Math.floor(diff / (1000 * 60 * 60 * 24));
diff -= days * (1000 * 60 * 60 * 24);
var hours = Math.floor(diff / (1000 * 60 * 60));
diff -= hours * (1000 * 60 * 60);
var mins = Math.floor(diff / (1000 * 60));
diff -= mins * (1000 * 60);
var seconds = Math.floor(diff / (1000));
diff -= seconds * (1000);
console.log(days + " days : " + hours + " hours : " + mins + " minutes : " + seconds + " seconds");
My solution is dirty but direct: calculate them by myself.
Record start time:
var BEGIN_TIME=new Date();
var HOUR=BEGIN_TIME.getHours();
var MINUTE=BEGIN_TIME.getMinutes();
var SECOND=BEGIN_TIME.getSeconds();
Then do so some math
var today=new Date();
h=today.getHours();
m=today.getMinutes();
s=today.getSeconds();
s = s - SECOND;
if (s<0) { s=s+60; m=m-1; }
m = m - MINUTE;
if (m<0) { m=m+60; h=h-1; }
h = h - HOUR;