Javascript countdown without Year - javascript

So I found this code on this site but there's one thing I want to change about it, but I can't seem to figure it out so I need some help. What I want to do is to remove the year in the date, so that the countdown corresponds the year that it is.
<script>
var end = new Date('04/19/2017 10:1 AM');
var _second = 1000;
var _minute = _second * 60;
var _hour = _minute * 60;
var _day = _hour * 24;
var timer;
function showRemaining() {
var now = new Date();
var distance = end - now;
if (distance < 0) {
clearInterval(timer);
document.getElementById('countdown').innerHTML = 'EXPIRED!';
return;
}
var days = Math.floor(distance / _day);
var hours = Math.floor((distance % _day) / _hour);
var minutes = Math.floor((distance % _hour) / _minute);
var seconds = Math.floor((distance % _minute) / _second);
document.getElementById('countdown').innerHTML = days + 'days ';
document.getElementById('countdown').innerHTML += hours + 'hrs ';
document.getElementById('countdown').innerHTML += minutes + 'mins ';
document.getElementById('countdown').innerHTML += seconds + 'secs';
}
timer = setInterval(showRemaining, 1000);
</script>
<div id="countdown"></div>
Credit for the code goes out to this guy

All you have to do is to create a new Date instance without any parameters. This will give you a Date object with the current datetime. But this is very insecure because your information will come from the browser (the client's machine). You should generate this on the server.
Whatever, if you don't know how to create that instance in Javascript, here you go:
var currentDatetime = new Date();
var currentYear = currentDatetime.getFullYear();
And then you can do something like this:
var end = new Date('04/19/' + currentYear + ' 10:1 AM');
You can explore what that Date class can do here: https://developer.mozilla.org/pt-BR/docs/Web/JavaScript/Reference/Global_Objects/Date

You should not parse strings with the Date constructor, they should be manually parsed with either a small function or library.
Assuming you have a date object, the year can be set using setFullYear, so:
// Create a date for 25 March, 2006
var d = new Date(2006, 2, 25);
console.log(d.toString());
// Set to current year
d.setFullYear(new Date().getFullYear());
console.log(d.toString());
If the date doesn't exist in the new year, e.g. if the starting date was 29 February 2016, then it rolls over to the next day, 1 March 2017.
If you know the date parts, you can go the other way and create a date and set the month and date, e.g.
// Create a date for 30 June in the current year
var d = new Date();
d.setMonth(5,30);
// Zero the time component
d.setHours(0,0,0,0);
console.log(d.toString());

Related

Count Down Stoped After Changed the Date

I was trying to implement count down timer for my web site. I want to give two static dates to and get the count down running. I found an example that uses one hard code date and the other date is taken as new Date() . but when I change that new Date() to Hard Code values count down timer stopped . How to fix this issue .
Original Example I found in jsfiddle.net
My modified Example in jsfiddle.net
the only difference in those examples is i changed var date1 = new Date(); to var date1 = new Date("2017/07/22 20:30:00");
The dates that you provided will never change since you are continually calling the same function each interval (i.e. the difference between date1 and date2 will never change).
If you want a countdown, you'll need to use some relatively changing date similar to the original example you provided or retain an offset (i.e. store when you started the process and continually use an offset for your calculations) as seen below:
// Store a relative date to track passing time
var started = new Date();
showDiff();
function showDiff() {
// Keep track of the time that has elapsed
var offset = new Date() - started;
// Store your dates
var date1 = new Date("2017/07/22 20:30:00") - offset;
var date2 = new Date("2015/07/30 21:59:00");
// Calculate the differences
var diff = Math.abs(Math.floor((date2 - date1) / 1000));
var days = Math.floor(diff / (24 * 60 * 60));
var daysLeft = diff - days * 24 * 60 * 60;
var hours = Math.floor(daysLeft / (60 * 60));
var hoursLeft = daysLeft - hours * 60 * 60;
var minutes = Math.floor(hoursLeft / (60));
var minutesLeft = hoursLeft - minutes * 60;
var seconds = Math.floor(minutesLeft / 60);
var secondsLeft = minutesLeft - seconds * 60;
// Output
document.getElementById("showTime").innerHTML = "You have " + days + " days " + hours + " hours " + minutes + " minutes and " + secondsLeft + " seconds before death.";
setTimeout(showDiff, 1000);
}
<div id='showTime'></div>

Javascript Countdown Timer - not working as expected

I have an issue in displaying counter between 2 dates. I know the issue and it is that Timezone is GMT+05:30
I need to know, how to rectify that
My Solution:
var start = new Date();
var end = new Date("2017-10-03"); // This date is coming from database as <?php echo $date_end; ?>
function getClock() {
var start = new Date();
var end = new Date("<?php echo $date_end; ?>");
var diff = Math.round((end.getTime() - start.getTime()) / 1000);
var hours = Math.floor(diff / 3600);
diff -= hours * 3600
var minutes = Math.floor(diff / 60);
diff -= minutes * 60;
var seconds = diff % 60;
if(document.getElementById('countdown')){
document.getElementById('countdown').innerHTML = "<span>"
+ hours + "</span> hours <span>" + minutes + "</span> minutes <span>"
+ seconds + "</span> seconds";
}
}
setInterval('getClock()', 1000);
As start date is 02 Oct 10PM and End date is 03 Oct. So as per time calculation i shall get timer of 2 hours
but i am getting timer is 2hours+5:30 = 7:30 hours.
Please help in getting right timer.
JS Fiddle link is HERE
You can get the timezone offset from the end date after you construct it, and then use that to reassign the value.
Here is a related question.
You can use the code from that post as follows:
var end = new Date("<?php echo $date_end; ?>");
end.setTime( end.getTime() + end.getTimezoneOffset()*60*1000 );
Try something like this.
setInterval(function(){
var start = new Date();
var end = new Date("2017-10-03 00:00:00");
var diff = Math.round((end.getTime() - start.getTime()) / 1000);
var hours = Math.floor(diff / 3600);
diff -= hours * 3600
var minutes = Math.floor(diff / 60);
diff -= minutes * 60;
var seconds = diff % 60;
if(document.getElementById('countdown')){
document.getElementById('countdown').innerHTML = "<span>"
+ hours + "</span> hours <span>" + minutes + "</span> minutes <span>"
+ seconds + "</span> seconds";
}
}, 1000);
The problem is because of the way Javascript handles timezones in the Date constructor (check out the documentation for details). If, instead of passing ("2017-10-03") you pass (2017, 9, 3), it should work. To avoid these kinds of problems, it is a good idea to always work in UTC.
Make sure you pass year, month and day separately to initialize the date, so the system timezone is used, same as when you initialize your start date:
var end_str = "<?php echo $date_end; ?>";
var arr = end_str.split("-")
arr = Date.new(arr[0], arr[1]-1, arr[2]); //month is 0-indexed

jQuery Countdown get time until 10:00 am today or tomorrow

I need a little script and I am a little confused.
I want to use this plugin: http://keith-wood.name/countdown.html
Goal: Have a Countdown, that counts from now to 10:00 am - if it's 0-9:59:59 am count to 10 o'clock today if it's after 10:00:00 count to 10:00 tomorrow.
Is that understandable?
Here's what I need with javascript / jquery (this will not work, i know):
var currentDate = new Date(new Date().getTime());
var hours = currentDate.getHours();
var endTime;
if(hours >= 10){
endTime = give me next day 10:00
} else {
endTime = give me this day 10:00
}
$("#countdown").countdown({until: endTime, format: 'HMS'});
The following should work (console.log() was added for testing purposes). Beware that it will use the timezone of the browser instead of UTC time.
var currentDate = new Date(new Date().getTime());
var hours = currentDate.getHours();
var endTime = new Date(currentDate);
endTime.setMinutes(0);
endTime.setSeconds(0);
endTime.setHours(10);
if(hours >= 10){
endTime.setDate(endTime.getDate() + 1);
}
console.log(endTime);
$("#countdown").countdown({until: endTime, format: 'HMS'});
You can handle it this way.
currentDate.setHours(10,00,00);
if(hours >= 10){
endTime = currentDate.AddDays(1);
}
This is the function I use for my website:
function countDown(id, date = "Jan 5 2018") {
var int = setInterval(function() {
// Get todays date and time
var now = new Date().getTime();
// Find the distance between now an the count down date
var distance = date - 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(id).innerHTML = days + "d " + hours + "h "
+ minutes + "m " + seconds + "s ";
// If the count down is finished, write some text
if (distance < 0) {
clearInterval(x);
document.getElementById(id).innerHTML = "00d 00h 00m 00s";
}
}, 1000);
return int;
}
In the date parameter, you need to enter your date and hour (ex. Jan 1, 2018 00:00:00) and in the id parameter the id selector (not '#myid' but only the name 'myid').
I hope this can be useful.
You can see it in action here
If you need the next day then increment the current date, then pass year, month, day and hours (static 10) to create the end date.
$(function() {
var currentDate = new Date();
var hours = currentDate.getHours();
var day;
if(hours >= 10){
day = currentDate.getDate() + 1;
} else {
day = currentDate.getDate();
}
var endTime = new Date(currentDate.getFullYear(), currentDate.getMonth(), day, 10);
$("#countdown").countdown({until: endTime, format: 'HMS'});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-countdown/2.0.2/jquery.plugin.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-countdown/2.0.2/jquery.countdown.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jquery-countdown/2.0.2/jquery.countdown.min.css" />
<div id='countdown'></div>

Javascript repeating countdown timer to midday

I am trying to create a javascript countdown which displays the hours and minutes, counting down to midday each day. When midday is reached I would like the timer to reset and start counting down to midday again (obviously to countdown to the following day).
I have the code below, however I just can't get it to work properly, the code works fine after midday however once midnight is reached the count is incorrect.
Here is my code:
function ShowTimes() {
var now = new Date();
var hrtime = now.getHours()
var hrs = 23 - hrtime + 12;
var mins = 59-now.getMinutes();
var secs = 59-now.getSeconds();
var str = '';
str += hrs+' hours '+mins+' minutes';
document.getElementById('countdown').innerHTML = str;
}
var _cntDown;
function StopTimes() {
clearInterval(_cntDown);
}
Any help is much appreciated! Thanks in advance.
Do you live somewhere that moves clocks forwards/backwards in spring/autumn?
If so, you'll have two days in the year where your hour and minute logic would fail.
Here's a way that works even when the clocks change:
var now = new Date();
var midday = new Date(now.getFullYear(), now.getMonth(), now.getDate() + (now.getHours() >= 12 ? 1 : 0), 12);
var millisToMidday = midday.getTime() - now.getTime();
var hours = Math.floor((millisToMidday / (60 * 60 * 1000)))
var minutes = Math.floor((millisToMidday / (60 * 1000))) % 60;
var seconds = Math.floor((millisToMidday / (1000))) % 60;
Change the logic for Hrs calculation as below :
if(hrtime>12)
hrtime=23- hrtime+ 12;
else
hrtime= 12-hrtime;

How to get time length from now back to the start of today (00h:00p:00s) in angularjs

How to get timelength from now back to the start of today (00h:00p:00s) in angularjs?
ex: now is 13:45. So timelength = 13*60 + 45 mins
There is no specificity in angular. Just use the Date object.
var date = new Date();
var timelength = date.getMinutes() + date.getHours() * 60;
Get a new JavaScript date object that represents the time now and then use the getHours and getMinutes functions to enable your calculation.
For example:
var now = new Date();
var hours = now.getHours();
var minutes = now.getMinutes();
var timeLength = hours*60 + minutes;
Converting a javascript date to a number gives you milliseconds since 1/1/1970 (UTC). You can correct for your time zone if you wish, then just take the modulus of the number of milliseconds in a day to get the number of milliseconds since midnight:
var dt = new Date();
var num = dt - dt.getTimezoneOffset() * 60000; // offset is in minutes
var sec = num / 1000; // seconds
var sinceMidnight = sec % (24 * 60 * 60); // seconds since midnight

Categories