How to reduce the cyclomatic complexity of this function? - javascript

I have a function that takes a timestamp in epoch (like 1517073001) and returns the time that has passed since then in a simple format like "2 hours ago" (not further verbosity like "2 hours, 31 minutes and 15 seconds ago").
The function works as intended but JSHint complains about using too many statements (30) and its cyclomatic complexity being too high (12). I was wondering what could be a way to improve these two aspects.
This is the function:
function msToTime(epoch) {
var previous = new Date(epoch * 1000);
var current = Math.floor(new Date().getTime());
var ms = current - previous;
var years = parseInt((ms / (1000 * 60 * 60 * 24 * 30 * 12)).toFixed(20), 10);
var months = parseInt((ms / (1000 * 60 * 60 * 24 * 30) % 12).toFixed(20), 10);
var days = parseInt((ms / (1000 * 60 * 60 * 24) % 30).toFixed(20), 10);
var hours = parseInt((ms / (1000 * 60 * 60) % 24).toFixed(20), 10);
var minutes = parseInt(ms / (1000 * 60) % 60, 10);
var seconds = parseInt(ms / 1000 % 60, 10);
var formatted = '';
if (years > 0) {
if (years > 1) {
formatted = years + ' years ago';
} else {
formatted = years + ' year ago';
}
} else if (months > 0) {
if (months > 1) {
formatted = months + ' months ago';
} else {
formatted = months + ' month ago';
}
} else if (days > 0) {
if (days > 1) {
formatted = days + ' days ago';
} else {
formatted = days + ' day ago';
}
} else if (hours > 0) {
if (hours > 1) {
formatted = hours + ' hours ago';
} else {
formatted = hours + ' hour ago';
}
} else if (minutes > 0) {
if (minutes > 1) {
formatted = minutes + ' minutes ago';
} else {
formatted = minutes + ' minute ago';
}
} else {
if (seconds > 1) {
formatted = seconds + ' seconds ago';
} else {
formatted = seconds + ' second ago';
}
}
return formatted;
}
var div = document.getElementById('time');
div.innerHTML = msToTime(1517073001);
<div id="time"></div>
Thank you in advance. :)

Another version optimized for divs and modules operations
function msToTime(epoch) {
var value = (Math.floor(new Date().getTime()) - new Date(epoch * 1000)) / 1000;
var time_factors = [['second', 60], ['minute', 60], ['hour', 24], ['day', 30], ['month', 12], ['year', NaN]];
for (factor of time_factors) {
if (value < factor[1] || isNaN(factor[1])) {
var t = Math.floor(value);
return t + ' ' + (t > 1 ? factor[0] + 's' : factor[0]) + ' ago';
}
value /= factor[1];
}
}

Replacing if...else if...else if... by switch (true) and putting the building of singular or plural to a function:
function msToTime(epoch) {
let previous = new Date(epoch * 1000);
let current = Math.floor(new Date().getTime());
let ms = current - previous;
let years = parseInt((ms / (1000 * 60 * 60 * 24 * 30 * 12)).toFixed(20), 10);
let months = parseInt((ms / (1000 * 60 * 60 * 24 * 30) % 12).toFixed(20), 10);
let days = parseInt((ms / (1000 * 60 * 60 * 24) % 30).toFixed(20), 10);
let hours = parseInt((ms / (1000 * 60 * 60) % 24).toFixed(20), 10);
let minutes = parseInt(ms / (1000 * 60) % 60, 10);
let seconds = parseInt(ms / 1000 % 60, 10);
let formatted = '';
function timeAgo(count, word) {
return `${count} ${(count === 1 ? word : word + 's')} ago`
}
switch (true) {
case years > 0:
formatted = timeAgo(years, 'year')
break
case months > 0:
formatted = timeAgo(months, 'month')
break
case days > 0:
formatted = timeAgo(days, 'day')
break
case hours > 0:
formatted = timeAgo(hours, 'hour')
break
case minutes > 0:
formatted = timeAgo(minutes, 'minute')
break
default:
formatted = timeAgo(seconds, 'second')
}
return formatted;
}
time.innerHTML = msToTime(1517073001);
<div id="time"></div>

Defining the date as array and iterating over it has decreased the Cyclomatic complexity number to 4(!), with only 12 statements.
function msToTime(epoch) {
var previous = new Date(epoch * 1000);
var current = Math.floor(new Date().getTime());
var ms = current - previous;
var formatted = '';
var completeDate = [
['year', parseInt((ms / (1000 * 60 * 60 * 24 * 30 * 12)).toFixed(20), 10)],
['month', parseInt((ms / (1000 * 60 * 60 * 24 * 30) % 12).toFixed(20), 10)],
['day', parseInt((ms / (1000 * 60 * 60 * 24) % 30).toFixed(20), 10)],
['hour', parseInt((ms / (1000 * 60 * 60) % 24).toFixed(20), 10)],
['minute', parseInt(ms / (1000 * 60) % 60, 10)],
['second', parseInt(ms / 1000 % 60, 10)]
];
for (var i = 0; i < completeDate.length; i++) {
var amount = completeDate[i][1];
if (amount > 0) {
var unit = completeDate[i][0];
formatted = amount + ' ' + (amount > 1 ? unit + 's' : unit) + ' ago';
break;
}
}
return formatted;
}
var div = document.getElementById('time');
div.innerHTML = msToTime(1517073001);
<div id="time"></div>
Thank you, #connexo, for the important advice!

function msToTime (epoch) {
var previous = new Date(epoch * 1000);
var current = Math.floor(new Date().getTime());
var ms = current - previous;
var years = parseInt((ms / (1000 * 60 * 60 * 24 * 30 * 12)).toFixed(20), 10);
var months = parseInt((ms / (1000 * 60 * 60 * 24 * 30) % 12).toFixed(20), 10);
var days = parseInt((ms / (1000 * 60 * 60 * 24) % 30).toFixed(20), 10);
var hours = parseInt((ms / (1000 * 60 * 60) % 24).toFixed(20), 10);
var minutes = parseInt(ms / (1000 * 60) % 60, 10);
var seconds = parseInt(ms / 1000 % 60, 10);
var formatted = '';
if (years > 0) {
formatted = years > 1 ? years + ' years ago' : years + ' year ago';
} else if (months > 0) {
formatted = months > 1 ? ' months ago' : ' month ago';
} else if (days > 0) {
formatted = days > 1 ? ' days ago' : ' day ago';
} else if (hours > 0) {
formatted = hours > 1 ? ' hours ago' : ' hour ago';
} else if (minutes > 0) {
formatted = minutes > 1 ? ' minutes ago' : ' minute ago';
} else {
formatted = seconds > 1 ? ' seconds ago' : ' second ago';
}
return formatted;
}
var div = document.getElementById('time');
div.innerHTML = msToTime(1417073002);
I have used JS ternary operator to shorten you code. Hope it helps.

Related

How can I make a countdown timer without days?

I'm looking for a way to have a countdown timer that displays more than 24 hours instead of displaying days when there is more than one day left. In short, it shows 26:04:32 instead of 01:02:04:32.
I was working with this, but got stuck.
<script>
(function () {
var deadline = '2022/09/07 00:00';
function pad(num, size) {
var s = "0" + num;
return s.substr(s.length - size);
}
// fixes "Date.parse(date)" on safari
function parseDate(date) {
const parsed = Date.parse(date);
if (!isNaN(parsed)) return parsed
return Date.parse(date.replace(/-/g, '/').replace(/[a-z]+/gi, ' '));
}
function getTimeRemaining(endtime) {
let total = parseDate(endtime) - Date.parse(new Date())
let seconds = Math.floor((total / 1000) % 60)
let minutes = Math.floor((total / 1000 / 60) % 60)
let hours = Math.floor((total / (1000 * 60 * 60)) % 24)
let days = Math.floor(total / (1000 * 60 * 60 * 24))
return { total, days, hours, minutes, seconds };
}
function clock(id, endtime) {
let days = document.getElementById(id + '-days')
let hours = document.getElementById(id + '-hours')
let minutes = document.getElementById(id + '-minutes')
let seconds = document.getElementById(id + '-seconds')
var timeinterval = setInterval(function () {
var time = getTimeRemaining(endtime);
if (time.total <= 0) {
clearInterval(timeinterval);
} else {
days.innerHTML = pad(time.days, 2);
hours.innerHTML = pad((time.hours, 2) + (24 * (time.days, 2)), 2);
minutes.innerHTML = pad(time.minutes, 2);
seconds.innerHTML = pad(time.seconds, 2);
}
}, 1000);
}
clock('js-clock', deadline);
})();
</script>
Just don't modulo (%) the hours with 24, and get rid of everything related to days:
let hours = Math.floor((total / (1000 * 60 * 60))); // will happily go > 24

how to check the diffrence between dates

I created a function to check the difference between a particular date and the current date, everything is working perfectly for past dates. But, when it comes to future dates, it gives the correct difference eg. the 18th of May is two days after the 16th of May, so the difference is 2, but I don't know if it's two days before or two days after. I cannot differentiate between future dates and past dates, whether the date is in the past or in the future.
here is my code:
function GetDateDiff(previousDate, previousTime) {
let today = new Date();
let dd = String(today.getDate()).padStart(2, "0");
let mm = String(today.getMonth() + 1).padStart(2, "0"); //January is 0!
let yyyy = today.getFullYear();
let currentDate = mm + "/" + dd + "/" + yyyy; // this will give you the current date
let previousMinutes = previousTime.split(":")[1];
let previousSeconds = previousTime.split(":")[2];
let previousHours = previousTime.split(":")[0];
let timePeriod = "seconds"; // timePeriod is the current unit of mesearement whether in seconds hours or days
let timeInNumber = "0"; //timeInNumber is the number infront of the timeperiod eg the 40 in 40 minites is the timeInNumber
let dateObj = new Date();
// this is to set the appropriate seconds, minutes and hours
if (currentDate == previousDate) {
if (dateObj.getHours() == previousHours) {
if (dateObj.getMinutes() == previousMinutes) {
timeInNumber = dateObj.getSeconds() - previousSeconds;
timePeriod = "Second";
} else {
timeInNumber = dateObj.getMinutes() - previousMinutes;
timePeriod = "Minute";
}
} else {
timeInNumber = dateObj.getHours() - previousHours;
timePeriod = "Hour";
// timePeriod =dateObj.getHours();
}
} else {
const previousDateDifferential = new Date(previousDate);
const currentDateDifferential = new Date(currentDate);
const diffrenceInDate = Math.abs(
currentDateDifferential - previousDateDifferential
);
// this is to calculate the diffrence in days, weeks, months and years
const diffDays = Math.ceil(diffrenceInDate / (1000 * 60 * 60 * 24));
const diffWeeks = Math.ceil(diffrenceInDate / (1000 * 60 * 60 * 24 * 7));
const diffMonths = Math.ceil(diffrenceInDate / (1000 * 60 * 60 * 24 * 7 * 4));
const diffyears = Math.ceil(diffrenceInDate / (1000 * 60 * 60 * 24 * 7 * 4 * 12));
// this is to set the appropriate days, weeks, months and years
if (diffDays <= 30) {
timeInNumber = diffDays;
timePeriod = "Day";
} else if (diffDays > 30 && diffWeeks <= 4) {
timeInNumber = diffWeeks;
timePeriod = "Week";
} else if (diffWeeks > 4 && diffMonths <= 12) {
timeInNumber = diffMonths - 2;
timePeriod = "Month";
} else if (diffMonths > 12) {
timeInNumber = diffyears - 1;
timePeriod = "Year";
}
}
if (timeInNumber > 1) {
timePeriod += "s"// this is to ad 's' at the end of the time period if the time period is more than 1
}
return `${timeInNumber} ${timePeriod} Ago`;
}
if I write GetDateDiff("05/14/2022", "00:00:00") // result will be 2 days ago
if I write GetDateDiff("05/18/2022", "00:00:00") // result will still be 2 days ago, how can i make it 2 days later or check that the date is in the future
The best tip was given already: use > and < to compare dates. Here is an example to get you started:
// function GetDateDiff to get the difference to the current date including negative values
function GetDateDiff(date) {
// get current date
var currentDate = new Date();
// get the difference between the current date and the date passed in
var diff = date.getTime() - currentDate.getTime();
// Build string prefix for negative and positive dates
var diffString = diff < 0 ? "In the Past: " : "In the Future: ";
// get the absolute value of the difference
diff = Math.abs(diff);
// get the days, hours, minutes, and seconds from the difference
var days = Math.floor(diff / (1000 * 60 * 60 * 24));
var hours = Math.floor((diff % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
var minutes = Math.floor((diff % (1000 * 60 * 60)) / (1000 * 60));
var seconds = Math.floor((diff % (1000 * 60)) / 1000);
// return the difference in days, hours, minutes, and seconds
return diffString + days + " days, " + hours + " hours, " + minutes + " minutes, " + seconds + " seconds";
}
// example usage
var date = new Date(2020, 0, 1, 0, 0, 0, 0);
var diff = GetDateDiff(date);
alert(diff);
var date = new Date(2024, 0, 1, 0, 0, 0, 0);
var diff = GetDateDiff(date);
alert(diff);
function GetDateDiff(previousDate, previousTime) {
let today = new Date();
let dd = String(today.getDate()).padStart(2, "0");
let mm = String(today.getMonth() + 1).padStart(2, "0"); //January is 0!
let yyyy = today.getFullYear();
let currentDate = mm + "/" + dd + "/" + yyyy; // this will give you the current date
let previousMinutes = previousTime.split(":")[1];
let previousSeconds = previousTime.split(":")[2];
let previousHours = previousTime.split(":")[0];
let timePeriod = "seconds"; // timePeriod is the current unit of mesearement whether in seconds hours or days
let timeInNumber = "0"; //timeInNumber is the number infront of the timeperiod eg the 40 in 40 minites is the timeInNumber
let timeWord = "Ago"
let dateObj = new Date();
// this is to set the appropriate seconds, minutes and hours
if (currentDate == previousDate) {
if (dateObj.getHours() == previousHours) {
if (dateObj.getMinutes() == previousMinutes) {
timeInNumber = dateObj.getSeconds() - previousSeconds;
timePeriod = "Second";
} else {
timeInNumber = dateObj.getMinutes() - previousMinutes;
timePeriod = "Minute";
}
} else {
timeInNumber = dateObj.getHours() - previousHours;
timePeriod = "Hour";
// timePeriod =dateObj.getHours();
}
}
else {
const previousDateDifferential = new Date(previousDate);
const currentDateDifferential = new Date(currentDate);
const diffrenceInDate = Math.abs(
currentDateDifferential - previousDateDifferential
);
// this is to calculate the diffrence in days, weeks, months and years
const diffDays = Math.ceil(diffrenceInDate / (1000 * 60 * 60 * 24));
const diffWeeks = Math.ceil(diffrenceInDate / (1000 * 60 * 60 * 24 * 7));
const diffMonths = Math.ceil(diffrenceInDate / (1000 * 60 * 60 * 24 * 7 * 4));
const diffyears = Math.ceil(diffrenceInDate / (1000 * 60 * 60 * 24 * 7 * 4 * 12));
// this is to set the appropriate days, weeks, months and years
if (diffDays <= 30) {
timeInNumber = diffDays;
timePeriod = "Day";
} else if (diffDays > 30 && diffWeeks <= 4) {
timeInNumber = diffWeeks;
timePeriod = "Week";
} else if (diffWeeks > 4 && diffMonths <= 12) {
timeInNumber = diffMonths - 2;
timePeriod = "Month";
} else if (diffMonths > 12) {
timeInNumber = diffyears - 1;
timePeriod = "Year";
}
if (currentDate < previousDate) {
timeWord = "Later"
}else {
timeWord = "Ago"
}
}
if (timeInNumber > 1) {
timePeriod += "s"// this is to ad 's' at the end of the time period if the time period is more than 1
}
return `${timeInNumber} ${timePeriod} ${timeWord}`;
}
GetDateDiff("05/14/2022", "00:00:00") // result will be 2 days ago
GetDateDiff("05/18/2022", "00:00:00") // result will be 2 days later

How do I factor in leap years when determining the difference between two dates using Javascript?

I'm trying to set up a counter to determine the difference between a set past date and the current date.
I have managed to set up a counter to determine the seconds between the two points, splitting the results into years, days, hours, minutes, seconds using the following code:
var lastDay = new Date("Jan 1, 1994 00:00:01").getTime();
var x = setInterval(function() {
var now = new Date().getTime();
var t = now - lastDay;
var years = Math.floor(t / (1000 * 60 * 60 * 24)/ 365);
var days = Math.floor((t % (1000 * 60 * 60 * 24 * 365))/(1000 * 60 * 60 * 24));
var hours = Math.floor((t % (1000 * 60 * 60 * 24))/(1000 * 60 * 60));
var minutes = Math.floor((t % (1000 * 60 * 60)) / (1000 * 60));
var seconds = Math.floor((t % (1000 * 60)) / 1000);
document.getElementById("year").innerHTML =years ;
document.getElementById("day").innerHTML =days ;
document.getElementById("hour").innerHTML =hours;
document.getElementById("minute").innerHTML = minutes;
document.getElementById("second").innerHTML =seconds;
if (t < 0) {
clearInterval(x);
document.getElementById("demo").innerHTML = "TIME UP";
document.getElementById("year").innerHTML ='0';
document.getElementById("day").innerHTML ='0';
document.getElementById("hour").innerHTML ='0';
document.getElementById("minute").innerHTML ='0' ;
document.getElementById("second").innerHTML = '0'; }
}, 1000);
The problem I have with this, is that it does not factor in leap years, therefore the 'days' figure is inaccurate. It should add another 7 days to account for the number of leap years between the set date and the current date (at time of writing).
I have tried to use the following code below to count the leap years:
var countLeapYears = function(){
var yearNow = new Date().getFullYear();
var then = new Date("Jan 1, 1994 00:00:01");
var yearThen = then.getFullYear();
var beginYear = 0;
var endYear = 0;
var leapYearCount = 0;
var isLeapYear = function(year){
return ((year % 4 === 0) && (year % 100 !== 0)) || (year % 400 === 0);
}
if(yearNow < y){
beginYear = yearNow;
endYear = yearThen;
}else if(yearNow > yearThen){
beginYear = yearThen;
endYear = yearNow;
}else if(yearNow == yearThen){
beginYear = yearThen;
endYear = yearThen;
}
for(i = beginYear; i <= endYear; i++){
if(isLeapYear(i)){
leapYearCount++;
}
}
return leapYearCount;
}
I then tried to add the 'leapYearCount' to the 'days' but it failed:
var countLeapYears = function(){
var yearNow = new Date().getFullYear();
var then = new Date("Jan 1, 1994 00:00:01");
var yearThen = then.getFullYear();
var beginYear = 0;
var endYear = 0;
var leapYearCount = 0;
var isLeapYear = function(year){
return ((year % 4 === 0) && (year % 100 !== 0)) || (year % 400 === 0);
}
if(yearNow < y){
beginYear = yearNow;
endYear = yearThen;
}else if(yearNow > yearThen){
beginYear = yearThen;
endYear = yearNow;
}else if(yearNow == yearThen){
beginYear = yearThen;
endYear = yearThen;
}
for(i = beginYear; i <= endYear; i++){
if(isLeapYear(i)){
leapYearCount++;
}
}
return leapYearCount;
}
var lastDay = new Date("Jan 1, 1994 00:00:01").getTime();
var x = setInterval(function() {
var now = new Date().getTime();
var t = now - lastDay;
var years = Math.floor(t / (1000 * 60 * 60 * 24)/ 365);
var days = Math.floor((t % (1000 * 60 * 60 * 24 * 365))/(1000 * 60 * 60 * 24) + leapYearCount);
var hours = Math.floor((t % (1000 * 60 * 60 * 24))/(1000 * 60 * 60));
var minutes = Math.floor((t % (1000 * 60 * 60)) / (1000 * 60));
var seconds = Math.floor((t % (1000 * 60)) / 1000);
document.getElementById("year").innerHTML =years ;
document.getElementById("day").innerHTML =days ;
document.getElementById("hour").innerHTML =hours;
document.getElementById("minute").innerHTML = minutes;
document.getElementById("second").innerHTML =seconds;
if (t < 0) {
clearInterval(x);
document.getElementById("demo").innerHTML = "TIME UP";
document.getElementById("year").innerHTML ='0';
document.getElementById("day").innerHTML ='0';
document.getElementById("hour").innerHTML ='0';
document.getElementById("minute").innerHTML ='0' ;
document.getElementById("second").innerHTML = '0'; }
}, 1000);
Any ideas how I can correct this and add the extra days to account for the number of leap years which have passed?
Many thanks.
The answer was a lot simpler than I had previously thought.
As I was just trying to factor in the difference in days because of the leap year, I just had to divide the number of years by 4 and add 1, like so:
var lastDay = new Date("Jan 1, 1994 10:00:00").getTime();
var x = setInterval(function() {
var now = new Date().getTime();
var t = now - lastDay;
var years = Math.floor(t / (1000 * 60 * 60 * 24)/ 365);
var leapDays = Math.floor((years / 4) + 1);
var days = Math.floor((t % (1000 * 60 * 60 * 24 * 365))/(1000 * 60 * 60 * 24) - leapDays);
var hours = Math.floor((t % (1000 * 60 * 60 * 24))/(1000 * 60 * 60));
var minutes = Math.floor((t % (1000 * 60 * 60)) / (1000 * 60));
var seconds = Math.floor((t % (1000 * 60)) / 1000);
document.getElementById("year").innerHTML =years ;
document.getElementById("day").innerHTML =days ;
document.getElementById("hour").innerHTML =hours;
document.getElementById("minute").innerHTML = minutes;
document.getElementById("second").innerHTML =seconds;
if (t < 0) {
clearInterval(x);
document.getElementById("demo").innerHTML = "TIME UP";
document.getElementById("year").innerHTML ='0';
document.getElementById("day").innerHTML ='0';
document.getElementById("hour").innerHTML ='0';
document.getElementById("minute").innerHTML ='0' ;
document.getElementById("second").innerHTML = '0'; }
}, 1000);

How to convert milliseconds into Days/hours/minutes

I am calculating the hours,minutes using the milliseconds. Below is mycode
function getDuration(milli){
let minutes = Math.floor(milli / 60000);
let hours = Math.round(minutes / 60);
}
I want to display the user the time as 'Days' if hours > 24 , 'minutes' if minute < 60. How can i implement it in template string in the following format
setHtml('Duration', `${getDuration(user[0].milli_seconds)} <span id="days">Hours</span> <span>Minutes</span>`);
You could return it as an object which returns days, hours or minutes depending on what is there.
function getDuration(milli){
let minutes = Math.floor(milli / 60000);
let hours = Math.round(minutes / 60);
let days = Math.round(hours / 24);
return (
(days && {value: days, unit: 'days'}) ||
(hours && {value: hours, unit: 'hours'}) ||
{value: minutes, unit: 'minutes'}
)
};
var tDuration = getDuration(23456576210);
console.log(tDuration.value + ': ' + tDuration.unit);
Original version:
function getDuration(milli){
let minutes = Math.floor(milli / 60000);
let hours = Math.round(minutes / 60);
let days = Math.round(hours / 24);
return (
(days && {days: days}) ||
(hours && {hours: hours}) ||
{minutes: minutes}
)
};
var tDuration = getDuration(23456576210);
console.log(tDuration);
Calculate days first , then hours and minutes
function convertToDays(milliSeconds){
let days = Math.floor(milliSeconds/(86400 * 1000));
milliSeconds -= days*(86400*1000);
let hours = Math.floor(milliSeconds/(60 * 60 * 1000 ));
milliSeconds -= hours * (60 * 60 * 1000);
let minutes = Math.floor(milliSeconds/(60 * 1000));
return {
days,hours,minutes
}
}
console.log(convertToDays(8640000));

Setting a custom countdown in javascript

My code is located below. I'm trying to set a countdown, however I can't figure out how to set the timer to operate. I've tried changing the "var setting". When I do it seems that the countdown works, however it glitches and the numbers appear but all go back to "0". Really confused. Someone Please help!
(function($) {
$.fn.countdown = function(options) {
var settings = { 'date': "30 september 2014 16:24:00" };
if(options) {
$.extend(settings, options);
}
this_sel = $(this);
function count_exec() {
eventDate = Date.parse(settings['date']) / 1000; // Parse the date string
currentDate = Math.floor($.now() / 1000); // Find the timestamp for now
seconds = eventDate - currentDate; // Find the number of seconds remaining
if (seconds <= 0) { // After the event date has passed
days = 0;
hours = 0;
minutes = 0;
seconds = 0;
} else {
days = Math.floor(seconds / (60 * 60 * 24)); // Divide to find the number of days remaining
seconds -= days * 60 * 60 * 24; // Subtract the number of (complete, => 24 hours) days calculated above
hours = Math.floor(seconds / (60 * 60)); // Get the number of hours from that modified number ^
seconds -= hours * 60 * 60;
minutes = Math.floor(seconds / 60);
seconds -= minutes * 60;
}
this_sel.find('#days').val(days).trigger('change');
this_sel.find('#hours').val(hours).trigger('change');
this_sel.find('#mins').val(minutes).trigger('change');
this_sel.find('#secs').val(seconds).trigger('change');
} // End of count_exec();
count_exec();
interval = setInterval(count_exec, 1000);
} // End of the main function
}) (jQuery);
Please but below code in your file and apply the desire date. It works fine for me. Let me know if any issue.
<body>
<form name="count">
<input type="text" size="69" name="count2">
</form>
<script type="text/javascript">
//change the text below to reflect your own,
var before = "Christmas!"
var current = "Today is Christmas. Merry Christmas!"
var montharray = new Array("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec")
function countdown(yr, m, d) {
theyear = yr; themonth = m; theday = d
var today = new Date()
var todayy = today.getYear()
if (todayy < 1000)
todayy += 1900
var todaym = today.getMonth()
var todayd = today.getDate()
var todayh = today.getHours()
var todaymin = today.getMinutes()
var todaysec = today.getSeconds()
var todaystring = montharray[todaym] + " " + todayd + ", " + todayy + " " + todayh + ":" + todaymin + ":" + todaysec
futurestring = montharray[m - 1] + " " + d + ", " + yr
dd = Date.parse(futurestring) - Date.parse(todaystring)
dday = Math.floor(dd / (60 * 60 * 1000 * 24) * 1)
dhour = Math.floor((dd % (60 * 60 * 1000 * 24)) / (60 * 60 * 1000) * 1)
dmin = Math.floor(((dd % (60 * 60 * 1000 * 24)) % (60 * 60 * 1000)) / (60 * 1000) * 1)
dsec = Math.floor((((dd % (60 * 60 * 1000 * 24)) % (60 * 60 * 1000)) % (60 * 1000)) / 1000 * 1)
if (dday == 0 && dhour == 0 && dmin == 0 && dsec == 1) {
document.forms.count.count2.value = current
return
}
else
document.forms.count.count2.value = "Only " + dday + " days, " + dhour + " hours, " + dmin + " minutes, and " + dsec + " seconds left until " + before
setTimeout("countdown(theyear,themonth,theday)", 1000)
}
//enter the Future count down date using the format year/month/day
countdown(2016, 9, 24)
</script>
</body>

Categories

Resources