Countdown in Javascript - javascript

I would like to put on our company intranet page the number of days until the next payday, however - the payday dates aren't every 4 weeks etc. they will be similar to this:
1st January 2011
15th February 2011
12th March 2011
20th April 2011
...
Is it possible to have a javascript countdown clock that has the above dates listed, so once one date has passed it would then start counting down until the next calendar date?
I can find plenty of examples of scripts that countdown until a specific date but none that start counting down to the second date once the first has passed.
Thanks,
Dan

Put the dates in an array. Be careful, in Javascript the months are zero-based so ranging from 0 to 11. Iterate the array and when the date is bigger then today display the days in between:
var calcPayDate = function () {
var payDates = [];
payDates.push(new Date(2011, 0, 1));
payDates.push(new Date(2011, 1, 15));
payDates.push(new Date(2011, 2, 12));
payDates.push(new Date(2011, 3, 20));
var today = new Date();
for (var i = 0; i < payDates.length; i++) {
if (payDates[i] > today) {
document.getElementById('countdownDiv').innerHTML = calcDays(payDates[i], today);
break;
}
}
}
var calcDays = function(date1, date2) {
// The number of milliseconds in one day
var ONE_DAY = 1000 * 60 * 60 * 24
// Convert both dates to milliseconds
var date1_ms = date1.getTime()
var date2_ms = date2.getTime()
// Calculate the difference in milliseconds
var difference_ms = Math.abs(date1_ms - date2_ms)
// Convert back to days and return
return Math.round(difference_ms / ONE_DAY)
}
The calcDays function is an function found on this site
The days are put in a div which is called 'countdownDiv'.

Search the web for "JavaScript tutorial".
Meanwhile, here's some code to get you started:
var dates = [
new Date(2011, 0, 1), // note that format is year, month-1, day
new Date(2011, 1, 15), // don't ask me why
new Date(2011, 2, 12),
new Date(2011, 3, 20)
];
var now = new Date();
for (var i in dates) { // this is a foreach loop
if (now < dates[i]) {
document.write(Math.ceil((dates[i] - now) / 86400000));
break;
}
}

Related

Date conversion Local to UTC and UTC to Local in Node.js

i want to change Local time to UTC and vice-versa, by taking users date value.(User will choose the dateand Time and according to dates it will change to UTC and vice versa )
Can someone help on this
If you have your date+time in a JavaScript Date object you can call its getUTCDate()method to get a new Date whose time zone is UTC.
If that is not what you have in mind please be more specific about what you mean by “it will change”.
You can try this:
function calculateTimestamp(date) {
date = date.split('-');
var year = date[2];
var month = date[1];
var day = date[0];
var d1 = new Date(Date.UTC(2017, 9, 1, 17, 0, 0, 0)); //It is static time based upon you will count time in ms
var d2 = new Date(Date.UTC(year, (month - 1), day, 17, 0, 0, 0));
return parseInt((d2.getTime() - d1.getTime()) / 1000);
}
var startDate = '27-02-2018';
var startTime = calculateTimestamp(startDate);
Now you can convert this timestamp again as below:
var d = new Date(Date.UTC(2017, 9, 1, 17, 0, 0, 0));
var t = parseInt(d.getTime() / 1000);
var d = new Date((startTime + t) * 1000);

Subtracting a specific date from today's date returns more than 3 days

Honestly, I don't know what's wrong. I'm using Flipclock javascript lib, and I'm trying to make a countdown to 15th January, 2015, 18:00 PM UTC. I tried many different approaches, and the one I currently have is which returns less numbers.
My code:
var clock;
$(document).ready(function (){
var nDate = new Date(2015, 01, 15, 18);
var currentDate = new Date();
var diff = (nDate.getTime() / 1000) - (currentDate.getTime() / 1000);
clock = $('.n-clock').FlipClock(diff, {
clockFace: 'DailyCounter',
autoStart: true,
countdown: true
});
});
Am I doing maths wrong? If so, please, tell me what's wrong.
Months are numbered from zero, so the following
var nDate = new Date(2015, 01, 15, 18);
Is February 15th.
Once you fix this, the result is correct. In Chrome:
> var nDate = new Date(2015, 0, 15, 18);
> var currentDate = new Date();
> var diff = (nDate.getTime() / 1000) - (currentDate.getTime() / 1000);
> diff / 24. / 3600.
< 2.894391319445438
(I.e. just under three days away.)

How can I find the difference between two dates in JavaScript?

I want to find the difference between two dates, inclusive. For example,
11/1/2014 (Nov 1) - 10/1/2014 (Oct 1) == 32 days
I was checking my results with the following page
var date1 = new Date(2013, 10, 01);
var date2 = new Date(2015, 10, 15);
var diff = new Date(date2.getTime() - date1.getTime());
console.log("diff.getUTCDate: " + diff.getUTCDate() );
// diff is: Thu Jul 05 1973 04:00:00 GMT+0300 (EEST)
if(diff.getUTCDate() == 1){
console.log(diff.getUTCDate() ); // Gives day count of difference
}else{
console.log( diff.getUTCDate() + 1 );
}
So I'm going to assume that you mean you want to calculate the number of days between 2 dates (including the end date). And you mistyped your example: between 10/01/2014 and 11/01/2014 - should return 32 days
So if that's the case, remove the time portion of the date and then do the date subtraction:
var d1 = new Date('October 01 2014'.replace('th',''));
var d2 = new Date('November 01 2014'.replace('th',''));
// remove the time portion, set the dates to midnight
d1.setHours(0,0,0,0);
d2.setHours(0,0,0,0);
var diff = Math.ceil((d2 - d1) / 86400000) + 1;
console.log(diff); //returns 32
Fiddle: http://jsfiddle.net/WJ5Rd/5/
If you don't want to do division with possibly large numbers, you can reduce the problem by making Date do some of the work for you
function isLeapYear(year) {
if (year % 4) return false;
if (year % 100) return true;
if (year % 400) return false;
return true;
}
function dayOfYear(date) {
var d1 = Date.UTC(date.getUTCFullYear(), 0, 0),
d2 = Date.UTC(date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate());
return (d2 - d1) / 864e5;
}
function daysBetween(start, end) {
var days = dayOfYear(end) - dayOfYear(start);
start = start.getUTCFullYear();
end = end.getUTCFullYear();
for (; start < end; ++start)
days += isLeapYear(start) ? 366 : 365;
return days;
}
Now it is just a case of
daysBetween(new Date(2014, 10-1, 1), new Date(2014, 11-1, 1)); // 32
This is good for if your time range will span decades or centuries
Otherwise just making a quick modification to dayOfYear gives
function countDays(start, end) {
var d1 = Date.UTC(start.getUTCFullYear(), start.getUTCMonth(), start.getUTCDate()),
d2 = Date.UTC(end.getUTCFullYear(), end.getUTCMonth(), end.getUTCDate());
return (d2 - d1) / 864e5;
}
Then
countDays(new Date(2014, 10-1, 1), new Date(2014, 11-1, 1)); // 32
Please note I used UTC for these calculations, this is just to avoid any daylight savings or other timezone changes
Include Moment.js for sane date handling. Then it's as easy as
var a = moment([2014,12,9])
var b = moment([2014,11,3])
a.diff(b, 'days') //37

Date difference larger than intended

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.

jquery/javascript- calculate days on this week given week number and year number

i'm looking for a simple way to calculate the calendar days when given a week and year number using jquery/javascript.
Example: Week 18, Year 2012 would result in a list of starting with sunday
2012-04-29
2012-04-30
2012-05-01
2012-05-02
2012-05-03
2012-05-04
2012-05-05
thanks
If you remake the code from this question you will get something like this:
function getDays(year, week) {
var j10 = new Date(year, 0, 10, 12, 0, 0),
j4 = new Date(year, 0, 4, 12, 0, 0),
mon = j4.getTime() - j10.getDay() * 86400000,
result = [];
for (var i = -1; i < 6; i++) {
result.push(new Date(mon + ((week - 1) * 7 + i) * 86400000));
}
return result;
}
DEMO: http://jsfiddle.net/TtmPt/
You need to decide what day begins a week - you specified Sunday. (ISO weeks start on Monday).
Get the day of the week of Jan 1.
Get the date of the closest Sunday.
If Jan 1 is on a Thursday, Friday, Saturday or Sunday, the first week of the year begins a week from the last Sunday in December. Otherwise, the first week of the year begins on the last Sunday of December.
Find the first day of any week of the year by setting the date to the first day + (weeks * 7) - 7.
var year= new Date().getFullYear(),
firstDay= new Date(year, 0, 1),
wd= firstDay.getDay();
firstDay.setDate(1 +(-1*(wd%7)));
if(wd>3){
firstDay.setDate(firstDay.getDate()+ 7);
}
var week4= new Date(firstDay);
week4.setDate(week4.getDate()+(4*7)- 7);
alert(week4);
returned value:(Date)
Sun Jan 20 2013 00: 00: 00 GMT-0500(Eastern Standard Time)
jquery/javascript- calculate days on this week given week number and year number
var years = $('#yr').val();
var weeks = $('#weekNo').val();
var d = new Date(years, 0, 1);
var dayNum = d.getDay();
var diff = --weeks * 7;
if (!dayNum || dayNum > 4) {
diff += 7;
}
d.setDate(d.getDate() - d.getDay() + ++diff);
$('#result').val(d);
[Demo] [1]: https://jsfiddle.net/2bhLw084/

Categories

Resources