I want to do a JavaScript loop based on two times (in military format), and that loop have to return a normal time.
For instance, I have this two vars:
var start_time = 1400; // That mens 14:00 or 2pm
var end_time = 400; // Or 0400 (but it's the same the browser. It's 04:00 or 4 am
I want to do a loop, a for or while, and I want to give as a result this:
14:00
15:00
16:00
....
3:00
4:00
How I can do that? Thanks!
start_time = start_time / 100;
end_time = end_time / 100;
var x = start_time;
while(x >= start_time || x <= end_time) {
if(x > 23) {
x = 0;
}
console.log(x + ":00");
x = x + 1;
}
http://jsfiddle.net/4R8Dr/1/
The general idea (room for improvement):
var start = 1400;
var end = 400;
if (start > end){
end = end + 2400;
}
for (var i = start; i <= end; i += 100)
{
var c = (i % 2400);
var s = c + '';
console.log(s.substring(0, c < 1000 ? 1 : 2) + ':00');
}
Output with node:
14:00
15:00
16:00
17:00
18:00
19:00
20:00
21:00
22:00
23:00
0:00
1:00
2:00
3:00
4:00
Loop in a for, incrementing the hour by 100.
Just make sure to reset loop variable to 0:00 when you reach 24:00
function loopHours(start_time, end_time) {
function write(hour){
console.log( (hour/100) + ":00" );
}
var hour = start_time;
for (; hour != end_time; hour += 100) {
if (hour >= 2400) {
hour = 0;
}
write(hour);
}
write(end_time);
}
getFormattedTime = function (fourDigitTime) {
var hours24 = parseInt(fourDigitTime.substring(0, 2), 10);
var hours = ((hours24 + 11) % 12) + 1;
var amPm = hours24 > 11 ? 'pm' : 'am';
var minutes = fourDigitTime.substring(2);
return hours + ':' + minutes + amPm;
};
$('span.mil_time').html(function (i, oldHtml) {
return getFormattedTime(oldHtml);
});
Plus a loop that increase/decreases the variable by 100 and resets at 2400 to 0000 will do what you need. Don't forget this function requires jQuery and span tags with the id "mil_time"
http://jsfiddle.net/FsN6L/
Related
I want to implement a simple javascript countdown that always counts down to the user's local next Friday, 15:00. I currently use the following code, but I believe that it only displays the countdown to next Friday, 15:00 UTC. Any help would really be appreciated!!
var curday;
var secTime;
var ticker;
function getSeconds() {
var nowDate = new Date();
var dy = 5; //Sunday through Saturday, 0 to 6
var countertime = new Date(nowDate.getFullYear(), nowDate.getMonth(), nowDate.getDate(), 15, 0, 0);
var curtime = nowDate.getTime(); //current time
var atime = countertime.getTime(); //countdown time
var diff = parseInt((atime - curtime) / 1000);
if (diff > 0) {
curday = dy - nowDate.getDay()
} else {
curday = dy - nowDate.getDay() - 1
} //after countdown time
if (curday < 0) {
curday += 7;
} //already after countdown time, switch to next week
if (diff <= 0) {
diff += (86400 * 7)
}
startTimer(diff);
}
function startTimer(secs) {
secTime = parseInt(secs);
ticker = setInterval("tick()", 1000);
tick(); //initial count display
}
function tick() {
var secs = secTime;
if (secs > 0) {
secTime--;
} else {
clearInterval(ticker);
getSeconds(); //start over
}
var days = Math.floor(secs / 86400);
secs %= 86400;
var hours = Math.floor(secs / 3600);
secs %= 3600;
var mins = Math.floor(secs / 60);
secs %= 60;
//update the time display
document.getElementById("days").innerHTML = curday;
document.getElementById("hours").innerHTML = ((hours < 10) ? "0" : "") + hours;
document.getElementById("minutes").innerHTML = ((mins < 10) ? "0" : "") + mins;
document.getElementById("seconds").innerHTML = ((secs < 10) ? "0" : "") + secs;
}
function starter() {
getSeconds();
}
Javascript dates are inherently UTC, however the various non–UTC get and set methods all work on local dates and times based on the host system clock and daylight saving settings.
So if you're not using UTC methods, everything in the OP is "local" by default. The following is a simplistic implementation of your "time until next Friday at 15:00" all as local values:
function timeUntil() {
let now = new Date();
// Create date for 15:00 on coming Friday
let friday = new Date(now);
friday.setHours(15,0,0,0);
let dayNum = friday.getDay();
friday.setDate(friday.getDate() + 5 - (dayNum < 6? dayNum : 5 - dayNum));
// If today is Friday and after 15:00, set to next Friday
if (dayNum == 5 && friday < now) {
friday.setDate(friday.getDate() + 7);
}
// Time remaining
let diff = friday - now;
let days = diff / 8.64e7 |0;
let hrs = (diff % 8.64e7) / 3.6e6 | 0;
let mins = (diff % 3.6e6) / 6e4 | 0;
let secs = (diff % 6e4) / 1e3 | 0;
// Display result
document.getElementById('days').textContent = days;
document.getElementById('hrs').textContent = hrs;
document.getElementById('mins').textContent = mins;
document.getElementById('secs').textContent = secs;
document.getElementById('fullDate').textContent = friday.toLocaleString();
}
setInterval(timeUntil, 1000);
td {
text-align: center;
}
<table>
<tr><th>Days<th>Hrs<th>Mins<th>Secs
<tr><td id="days"><td id="hrs"><td id="mins"><td id="secs">
<tr><td id="fullDate" colspan="4">
</table>
Note that setInterval isn't a good way to run a timer over a long period as it drifts (it doesn't run at exactly the specified interval). The overall time will be OK, it will just seem to skip from time to time and drift within a second with respect to the system displayed clock.
Better to use sequential calls setTimeout, calculating the time until just after the next full second each time so it closely matches the system clock's tick.
I have a countdown script that enables me to see how much time there is left until a specific date and time in any given timezone. The script has improved alot from its original state (Much thanks to this community) but it still has some flaws.
The script is currently only able to countdown to a specific hour (Like 2015/12/12 18:00) but NOT to a specific minute (Like 2015/12/12 18:25).
I would like to be able to also specify any given minute of the hour (var minute), but I dont know how. Would greatly apreciate if anyone could help me out.
Edit: The timezone variable (var tz) must be taken into account.
Edit2: Solved the issue I got with the first answer, with this: toDate.setMinutes(minutes-(tz*60));
Full script below:
////////// CONFIGURE THE COUNTDOWN SCRIPT HERE //////////////////
var month = '11'; // '*' for next month, '0' for this month or 1 through 12 for the month
var day = '10'; // Offset for day of month day or + day
var hour = 14; // 0 through 23 for the hours of the day
var tz = -5; // Offset for your timezone in hours from UTC
var lab = 'tzcd'; // The id of the page entry where the timezone countdown is to show
function start() {displayTZCountDown(setTZCountDown(year,month,day,hour,tz),lab);}
// ** The start function can be changed if required **
window.onload = start;
////////// DO NOT EDIT PAST THIS LINE //////////////////
function setTZCountDown(year,month,day,hour,tz)
{
// props to Luke Woodward at Stackoverflow
var now = new Date();
var countdownToYear = now.getFullYear();
var countdownToMonth = now.getMonth();
var countdownToDay = now.getDate();
if (month === '*') {
countdownToMonth += 1;
} else if (month > 0) {
if (month <= now.getMonth()) {
countdownToYear += 1;
}
countdownToMonth = month - 1;
}
if (day.substr(0,1) === '+') {
var day1 = parseInt(day.substr(1), 10);
countdownToDay += day1;
} else {
countdownToDay = day;
}
var toDate = new Date(countdownToYear, countdownToMonth, countdownToDay);
// props to Luke Woodward at Stackoverflow^
toDate.setHours(hour);
toDate.setMinutes(0-(tz*60));
toDate.setSeconds(0);
var fromDate = new Date();
fromDate.setMinutes(fromDate.getMinutes() + fromDate.getTimezoneOffset());
var diffDate = new Date(0);
diffDate.setMilliseconds(toDate - fromDate);
return Math.floor(diffDate.valueOf()/1000);
}
function displayTZCountDown(countdown,tzcd)
{
if (countdown < 0) document.getElementById(tzcd).innerHTML = "<li>0<br><span class='tzcd-format'>day</span></li><li>0<br><span class='tzcd-format'>hours</span></li><li>0<br><span class='tzcd-format'>minutes</span></li><li>0<br><span class='tzcd-format'>seconds</span></li>";
else {var secs = countdown % 60;
if (secs < 10) secs = '0'+secs;
var countdown1 = (countdown - secs) / 60;
var mins = countdown1 % 60;
if (mins < 10) mins = '0'+mins;
countdown1 = (countdown1 - mins) / 60;
var hours = countdown1 % 24;
var days = (countdown1 - hours) / 24;
document.getElementById(tzcd).innerHTML = "<li>" + days + "<br><span class='tzcd-format'>day" + (days == 1 ? '' : 's') + '</span></li>' + "<li>" + hours + "<br><span class='tzcd-format'>hours</span></li> " + "<li>" + mins + "<br><span class='tzcd-format'>minutes</span></li>" +"<li>"+secs+ "<br><span class='tzcd-format'>seconds</span></li>";
setTimeout('displayTZCountDown('+(countdown-1)+',\''+tzcd+'\');',999);
}
}
I wasn't able to test it but this should be it:
////////// CONFIGURE THE COUNTDOWN SCRIPT HERE //////////////////
var month = '11'; // '*' for next month, '0' for this month or 1 through 12 for the month
var day = '10'; // Offset for day of month day or + day
var hour = 14; // 0 through 23 for the hours of the day
var tz = -5; // Offset for your timezone in hours from UTC
var minutes = '10';
var lab = 'tzcd'; // The id of the page entry where the timezone countdown is to show
function start() {displayTZCountDown(setTZCountDown(year,month,day,hour,tz),lab);}
// ** The start function can be changed if required **
window.onload = start;
////////// DO NOT EDIT PAST THIS LINE //////////////////
function setTZCountDown(year,month,day,hour,tz)
{
// props to Luke Woodward at Stackoverflow
var now = new Date();
var countdownToYear = now.getFullYear();
var countdownToMonth = now.getMonth();
var countdownToDay = now.getDate();
if (month === '*') {
countdownToMonth += 1;
} else if (month > 0) {
if (month <= now.getMonth()) {
countdownToYear += 1;
}
countdownToMonth = month - 1;
}
if (day.substr(0,1) === '+') {
var day1 = parseInt(day.substr(1), 10);
countdownToDay += day1;
} else {
countdownToDay = day;
}
var toDate = new Date(countdownToYear, countdownToMonth, countdownToDay);
// props to Luke Woodward at Stackoverflow^
toDate.setHours(hour);
toDate.setMinutes(minutes);
toDate.setSeconds(0);
var fromDate = new Date();
fromDate.setMinutes(fromDate.getMinutes() + fromDate.getTimezoneOffset());
var diffDate = new Date(0);
diffDate.setMilliseconds(toDate - fromDate);
return Math.floor(diffDate.valueOf()/1000);
}
function displayTZCountDown(countdown,tzcd)
{
if (countdown < 0) document.getElementById(tzcd).innerHTML = "<li>0<br><span class='tzcd-format'>day</span></li><li>0<br><span class='tzcd-format'>hours</span></li><li>0<br><span class='tzcd-format'>minutes</span></li><li>0<br><span class='tzcd-format'>seconds</span></li>";
else {var secs = countdown % 60;
if (secs < 10) secs = '0'+secs;
var countdown1 = (countdown - secs) / 60;
var mins = countdown1 % 60;
if (mins < 10) mins = '0'+mins;
countdown1 = (countdown1 - mins) / 60;
var hours = countdown1 % 24;
var days = (countdown1 - hours) / 24;
document.getElementById(tzcd).innerHTML = "<li>" + days + "<br><span class='tzcd-format'>day" + (days == 1 ? '' : 's') + '</span></li>' + "<li>" + hours + "<br><span class='tzcd-format'>hours</span></li> " + "<li>" + mins + "<br><span class='tzcd-format'>minutes</span></li>" +"<li>"+secs+ "<br><span class='tzcd-format'>seconds</span></li>";
setTimeout('displayTZCountDown('+(countdown-1)+',\''+tzcd+'\');',999);
}
}
I'm using JQuery Datepicker for customers to choose a delivery date. I want to be able to check if the customer is ordering before noon and if so next day delivery is available. If they are ordering after noon, next day delivery is unavailable and so that day is unselectable.
I've got some code to check against the current time but how to I add this value into MinDate in the settings at the top?
Thank you!
<div class="delivery-date">
<p>
<label for="date">Select a date for delivery below:</label>
<input id="date" type="text" name="properties[delivery-date]" readonly="readonly" style="background:white; width:30%" class="required" data-error="Please choose a delivery date." />
</p>
</div>
<script>
jQuery(function() {
jQuery("#date").datepicker( {
// minDate: new Date(((new Date).getTime() + 49 * 60 * 60 * 1000) ),
minDate: checkBeforeNoon,
maxDate: "+2M", // show up to 2 months
dateFormat: 'dd/mm/yy',
beforeShowDay: available_delivery_dates
} );
});
/*========== check time ==========*/
// if time before 12pm, offer next day delivery
function checkBeforeNoon(nextDayDelivery){
var startTime = '12:00 AM';
var endTime = '12:00 PM';
var curr_time = getval();
if (get24Hr(curr_time) > get24Hr(startTime) && get24Hr(curr_time) < get24Hr(endTime)) {
// before 12pm - next day delivery available
var nextDayDelivery = '+1d';
} else {
// after 12pm - next day delivery unavailable
var nextDayDelivery = '+2d';
}
function get24Hr(time){
var hours = Number(time.match(/^(\d+)/)[1]);
var AMPM = time.match(/\s(.*)$/)[1];
if(AMPM == "PM" && hours<12) hours = hours+12;
if(AMPM == "AM" && hours==12) hours = hours-12;
var minutes = Number(time.match(/:(\d+)/)[1]);
hours = hours*100+minutes;
console.log(time +" - "+hours);
return hours;
}
function getval() {
var currentTime = new Date()
var hours = currentTime.getHours()
var minutes = currentTime.getMinutes()
if (minutes < 10) minutes = "0" + minutes;
var suffix = "AM";
if (hours >= 12) {
suffix = "PM";
hours = hours - 12;
}
if (hours == 0) {
hours = 12;
}
var current_time = hours + ":" + minutes + " " + suffix;
return current_time;
}
}
/*========== Make sundays always unavailable ==========*/
function available_delivery_dates(date) {
var sunday = 0; // unavailable for delivery
var mon = 1
var tue = 2;
var wed = 3;
var thu = 4;
var fri = 5;
var sat = 6;
var day_of_week = date.getDay();
var not_sun = day_of_week > 0;
if(not_sun){
var day = date.getDate();
return [true, ''];
}
else{
// all else - do not allow
return [false, ' ', 'Delivery is unavailable on this day'];
}
}
</script>
You already accomplished it. You simply need to add a return to the function that is checking if it is noon. If you want to advise the client that one day shipping is available now, you can do so by adding a log in your function. Here is your code modified:
http://jsfiddle.net/graphicfreedom/L3tz8243/1/
function checkBeforeNoon(nextDayDelivery){
var startTime = '12:00 AM';
var endTime = '12:00 PM';
var curr_time = getval();
if (get24Hr(curr_time) > get24Hr(startTime) && get24Hr(curr_time) < get24Hr(endTime)) {
// before 12pm - next day delivery available
var nextDayDelivery = '+1d';
$("#log").html('Next day delivery available! Order before noon!'); //show response to user
} else {
// after 12pm - next day delivery unavailable
var nextDayDelivery = '+2d';
$("#log").html('Next day delivery NOT available! It is already past noon :('); //show response to user
}
return nextDayDelivery;
}
Also, you can easily separate the functions. It is easier to read, and you can always call a function from a function. Hope this helps!
Remove the var before nextDayDelivery in the if-else block as you would be redeclaring it. Then return nextDayDelivery. Also, a good idea to fix the missing semi-colons in the getVal() method.
function checkBeforeNoon(nextDayDelivery) {
var startTime = '12:00 AM';
var endTime = '12:00 PM';
var curr_time = getval();
if (get24Hr(curr_time) > get24Hr(startTime) && get24Hr(curr_time) < get24Hr(endTime)) {
// before 12pm - next day delivery available
nextDayDelivery = '+1d'; // REMOVE var FROM HERE
} else {
// after 12pm - next day delivery unavailable
nextDayDelivery = '+2d'; // REMOVE var FROM HERE
}
function get24Hr(time) {
var hours = Number(time.match(/^(\d+)/)[1]);
var AMPM = time.match(/\s(.*)$/)[1];
if (AMPM == "PM" && hours < 12) hours = hours + 12;
if (AMPM == "AM" && hours == 12) hours = hours - 12;
var minutes = Number(time.match(/:(\d+)/)[1]);
hours = hours * 100 + minutes;
console.log(time + " - " + hours);
return hours;
}
function getval() {
// ADD MISSING SEMI-COLONS ON THE FOLLOWING 3 LINES
var currentTime = new Date();
var hours = currentTime.getHours();
var minutes = currentTime.getMinutes();
if (minutes < 10) minutes = "0" + minutes;
var suffix = "AM";
if (hours >= 12) {
suffix = "PM";
hours = hours - 12;
}
if (hours == 0) {
hours = 12;
}
var current_time = hours + ":" + minutes + " " + suffix;
return current_time;
}
return nextDayDelivery; // ADD RETURN STATEMENT
}
I have the following JavaScript on my site that shows the amount of time left for an order to be placed for next day delivery.
if (document.getElementById('countdownTimer')) {
pad = function(n, len) { // leading 0's
var s = n.toString();
return (new Array((len - s.length + 1)).join('0')) + s;
};
var timerRunning = setInterval(
function countDown() {
var now = new Date();
if ((now.getDay() >= 1) && (now.getDay() <= 5)) { // Monday to Friday only
var target = 15; // 15:00hrs is the cut-off point
if (now.getHours() < target) { // don't do anything if we're past the cut-off point
var hrs = (target - 1) - now.getHours();
if (hrs < 0) hrs = 0;
var mins = 59 - now.getMinutes();
if (mins < 0) mins = 0;
var secs = 59 - now.getSeconds();
if (secs < 0) secs = 0;
var str = pad(hrs, 2) + ':' + pad(mins, 2) + '.<small>' + pad(secs, 2) + '</small>';
document.getElementById('countdownTimer').innerHTML = str;
}
}
}, 1000
);
}
The problem with this is that on saturday and sunday it just displays 00:00:00 all the time.
What I would like it to do is count the hours over a weekend as is done on this site for example: http://www.nakedwines.com/full_site
JavaScript is really not my area and I'm totally at a loss on how I can change the code to do this. Any help would be appreciated.
Fiddle is here http://jsfiddle.net/rwet0o5f/
I've moved the now.getDay() into variable and now it should be much more readable.
weekday contains 0 on Sunday, 1 on Monday and 6 on Saturday.
On Saturday we add 48 hours to the time of the deadline,
On Sunday we add only 24 hours.
http://jsfiddle.net/37ox54bk/7/
if (document.getElementById('countdownTimer')) {
pad = function(n, len) { // leading 0's
var s = n.toString();
return (new Array( (len - s.length + 1) ).join('0')) + s;
};
var timerRunning = setInterval(
function countDown() {
var target = 15; // 15:00hrs is the cut-off point
var now = new Date();
//Put this in a variable for convenience
var weekday = now.getDay();
if(weekday == 0){//Sunday? Add 24hrs
target += 24;
}
if(weekday == 6){//It's Saturday? Add 48hrs
target += 48;
}
//If between Monday and Friday,
//check if we're past the target hours,
//and if we are, abort.
if((weekday>=1) && (weekday<=5)){
if (now.getHours() > target) { //stop the clock
return 0;
}
}
var hrs = (target - 1) - now.getHours();
if (hrs < 0) hrs = 0;
var mins = 59 - now.getMinutes();
if (mins < 0) mins = 0;
var secs = 59 - now.getSeconds();
if (secs < 0) secs = 0;
var str = pad(hrs, 2) + ':' + pad(mins, 2) + '.<small>' + pad(secs, 2) + '</small>';
document.getElementById('countdownTimer').innerHTML = str;
}, 1000
);
}
Try this.
Instead of not doing anything when you are past the target time, I just increase the target time to point to a different day (the main difference is the if..else if statements at the beginning of the function)
function countDown() {
var now = new Date();
var target = 15; // 15:00hrs is the cut-off point
if (now.getDay() == 0) { // Sunday - use tomorrow's cutoff
target += 24;
} else if (now.getDay() == 6) { // Saturday - use cutoff 2 days from now
target += 48;
} else if (now.getHours() < target) { // missed the cutoff point. Use tomorrow instead
target += 24;
if (now.getDay() == 5) { // Friday - use Monday cutoff
target += 48;
}
}
var hrs = (target - 1) - now.getHours();
if (hrs < 0)
hrs = 0;
var mins = 59 - now.getMinutes();
if (mins < 0)
mins = 0;
var secs = 59 - now.getSeconds();
if (secs < 0)
secs = 0;
var str = pad(hrs, 2) + ':' + pad(mins, 2) + '.<small>' + pad(secs, 2) + '</small>';
document.getElementById('countdownTimer').innerHTML = str;
}, 1000);
I forked the fiddle: http://jsfiddle.net/4vhah8yt/1/
Code #sEver is good. Aj Richardson your code countdown is from new hours - is wrong.
I'd like to affter countdown hide HTML/CSS code.
Full Code: https://codepen.io/kamikstudio/pen/dyzvrQP
if (document.getElementById('countdownTimer')) {
pad = function(n, len) { // leading 0's
var s = n.toString();
return (new Array( (len - s.length + 1) ).join('0')) + s;
};
var timerRunning = setInterval(
function countDown() {
var target = 14; // 15:00hrs is the cut-off point
var now = new Date();
//Put this in a variable for convenience
var weekday = now.getDay();
if(weekday == 0){//Sunday? Add 24hrs
target += 24;
}
if(weekday == 6){//It's Saturday? Add 48hrs
target += 48;
}
//If between Monday and Friday,
//check if we're past the target hours,
//and if we are, abort.
if((weekday>=1) && (weekday<=5)){
if (now.getHours() > target) { //stop the clock
return 0;
}
}
var hrs = (target - 1) - now.getHours();
if (hrs < 0) hrs = 0;
var mins = 59 - now.getMinutes();
if (mins < 0) mins = 0;
var secs = 59 - now.getSeconds();
if (secs < 0) secs = 0;
var str = '<b>' + pad(hrs, 2) + ' </b>hours<b> ' + pad(mins, 2) + ' </b>min<b> ' + pad(secs, 2) + ' </b>sec';
document.getElementById('countdownTimer').innerHTML = str;
}, 1000
);
}
I am getting the time duration correctly for 24 hrs format but for 12 hrs format I am getting error if i give 11:00 am to 1:00 pm. If I give 10:00 am to 11:00 am it will correctl and if I give 6:00 pm to 7:00 pm it will give correctly only in am to pm i m facing problem.
function autoChangeDuration() {
var diff1 = "00:00";
var start = document.getElementById("startTime").value;
var end = document.getElementById("endTime").value;
if (start > end) {
document.getElementById("duration").value = diff1;
} else {
var space1 = start.split(' ');
var space2 = end.split(' ');
s = space1[0].split(':');
e = space2[0].split(':');
var diff;
min = e[1] - s[1];
hour_carry = 0;
if (min < 0) {
min += 60;
hour_carry += 1;
}
hour = e[0] - s[0] - hour_carry;
diff = hour + ":" + min;
document.getElementById("duration").value = diff;
}
function toDate(s) {
// the date doesn't matter, as long as they're the same, since we'll
// just use them to compare. passing "10:20 pm" will yield 22:20.
return new Date("2010/01/01 " + s);
}
function toTimeString(diffInMs) {
// Math.max makes sure that you'll get '00:00' if start > end.
var diffInMinutes = Math.max(0, Math.floor(diffInMs / 1000 / 60));
var diffInHours = Math.max(0, Math.floor(diffInMinutes / 60));
diffInMinutes = diffInMinutes % 60;
return [
('0'+diffInHours).slice(-2),
('0'+diffInMinutes).slice(-2)
].join(':');
}
function autoChangeDuration()
{
var start = document.getElementById("startTime").value;
var end = document.getElementById("endTime").value;
start = toDate(start);
end = toDate(end);
var diff = (end - start);
document.getElementById("duration").value = toTimeString(diff);
}
Why don't you just use javascript's Date class?
http://www.w3schools.com/jsref/jsref_obj_date.asp