How to start my JS countdown 2pm to 2pm? - javascript

Currently, it is working for 12am to 12am but I want it 2pm to 2pm. Is it possible?
setInterval(
function() {
var d = new Date();
var hours = 23 - d.getHours();
var min = 59 - d.getMinutes();
if ((min + '').length == 1) {
min = '0' + min;
}
var sec = 59 - d.getSeconds();
if ((sec + '').length == 1) {
sec = '0' + sec;
}
$('#the-final-countdown').html(hours + ':' + min + ':' + sec);
},
1000);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="the-final-countdown"></div>

setInterval(function time(){
var d = new Date();
if(d.getHours()<=13){
var hours = (13 - d.getHours());
}else{
var hours = (23+14 - d.getHours())
}
var min = 59 - d.getMinutes();
if((min + '').length == 1){
min = '0' + min;
}
var sec = 59 - d.getSeconds();
if((sec + '').length == 1){
sec = '0' + sec;
}
jQuery('#the-final-countdown p').html(hours+':'+min+':'+sec)
}, 1000);

A simple way to create a count down to 14:00 is to get the difference between now and the next time it will be 14:00, then convert to h:mm:ss, e.g.
// Returns milliseconds from date until next 1400
// Default for date is current time
function next1400(date) {
var now = date || new Date();
var end = new Date(now);
end.setHours(end.getHours() < 14? 14 : 38, 0, 0, 0);
return formatTime(end - now);
}
// Format milliseconds as H:mm:ss
function formatTime(ms) {
var s = Math.ceil(ms/1e3);
function z(n){return (n<10?'0':'')+n}
return (s/3.6e3 | 0) + ':' +
z((s%3.6e3)/60 | 0) + ':' +
z(s%60) ;
}
// QnD way to call each second. This will skip occasionally,
// there are better ways.
setInterval(function(){
console.log(next1400());
}, 1000);

Related

Countdown timer daily loop

I'm want to use a countdown timer to count to 10am every day so I am using this:
setInterval(function time(){
var d = new Date();
var hours = 09 - d.getHours();
var min = 60 - d.getMinutes();
if((min + '').length == 1){
min = '0' + min;
}
var sec = 60 - d.getSeconds();
if((sec + '').length == 1){
sec = '0' + sec;
}
jQuery('#countdown p').html('<span>'+hours+'</span><span class="mins">'+min+'<br></span><span class="secs">'+sec+'</span>')
}, 1000)
However, after 10am it obviously wants to turn negative, so I want to add in something to add 24hr after 10am like:
if(hours >= 10){
d = new Date() + 1;
}
but cannot get it working, any thoughts would be greatly appreciated.
You want to set hours and then use getDate() method.
setInterval(function time(){
var start = new Date;
start.setHours(10, 0, 0); // 10am
var now = new Date;
if (now > start) { // check current time is getter then add one day
start.setDate(start.getDate() + 1);
}
var days = ((start - now) / 1000);
var hours = format((days / 60 / 60) % 60);
var min = format((days / 60) % 60);
var sec = format(days % 60);
jQuery('#countdown p').html('<span>'+hours+'</span><span class="mins">'+min+'<br></span><span class="secs">'+sec+'</span>')
},1000);
// Add before 0 of hour, min, sec
function format(num) {
return ("0" + parseInt(num)).substr(-2);
}
Try Using A library like https://momentjs.com/
it will save you many lines of code.

How to set Am and Pm for Clock [duplicate]

I have buttons with the names of big cities.
Clicking them, I want to get local time in them.
$('#btnToronto').click(function () {
var hours = new Date().getHours();
var hours = hours-2; //this is the distance from my local time
alert ('Toronto time: ' + hours + ' h'); //this works correctly
});
But how can I get AM or PM ?
You should just be able to check if hours is greater than 12.
var ampm = (hours >= 12) ? "PM" : "AM";
But have you considered the case where the hour is less than 2 before you subtract 2? You'd end up with a negative number for your hour.
Try below code:
$('#btnToronto').click(function () {
var hours = new Date().getHours();
var hours = (hours+24-2)%24;
var mid='am';
if(hours==0){ //At 00 hours we need to show 12 am
hours=12;
}
else if(hours>12)
{
hours=hours%12;
mid='pm';
}
alert ('Toronto time: ' + hours + mid);
});
You can use like this,
var dt = new Date();
var h = dt.getHours(), m = dt.getMinutes();
var _time = (h > 12) ? (h-12 + ':' + m +' PM') : (h + ':' + m +' AM');
Hopes this will be better with minutes too.
const now = new Date()
.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit', hour12: true })
.toLowerCase();
Basically you just need to put {hour12: true} and it's done.
result => now = "21:00 pm";
If hours is less than 12, it's the a.m..
var hours = new Date().getHours(), // this is local hours, may want getUTCHours()
am;
// adjust for timezone
hours = (hours + 24 - 2) % 24;
// get am/pm
am = hours < 12 ? 'a.m.' : 'p.m.';
// convert to 12-hour style
hours = (hours % 12) || 12;
Now, for me as you didn't use getUTCHours, it is currently 2 hours after
hours + ' ' + am; // "6 p.m."
very interesting post. in a function that take a date in parameter it can appear like that :
function hourwithAMPM(dateInput) {
var d = new Date(dateInput);
var ampm = (d.getHours() >= 12) ? "PM" : "AM";
var hours = (d.getHours() >= 12) ? d.getHours()-12 : d.getHours();
return hours+' : '+d.getMinutes()+' '+ampm;
}
with date.js
<script type="text/javascript" src="http://www.datejs.com/build/date.js"></script>
you can write like this
new Date().toString("hh:mm tt")
cheet sheet is here format specifiers
tt is for AM/PM
Try this:
h = h > 12 ? h-12 +'PM' : h +'AM';
The best way without extensions and complex coding:
date.toLocaleString([], { hour12: true});
How do you display javascript datetime in 12 hour AM/PM format?
here is get time i use in my code
let current = new Date();
let cDate = current.getDate() + '-' + (current.getMonth() + 1) + '-' + current.getFullYear();
let hours = current.getHours();
let am_pm = (hours >= 12) ? "PM" : "AM";
if(hours >= 12){
hours -=12;
}
let cTime = hours + ":" + current.getMinutes() + ":" + current.getSeconds() +" "+ am_pm;
let dateTime = cDate + ' ' + cTime;
console.log(dateTime); // 1-3-2021 2:28:14 PM
var now = new Date();
var hours = now.getHours();
var minutes = now.getMinutes();
var ampm = hours >= 12 ? 'pm' : 'am';
hours = hours % 12;
hours = hours ? hours : 12;
minutes = minutes < 10 ? '0' + minutes : minutes;
var timewithampm = hours + ':' + minutes + ' ' + ampm;
return timewithampm;
var dt = new Date();
var h = dt.getHours(),
m = dt.getMinutes();
var time;
if (h == 12) {
time = h + ":" + m + " PM";
} else {
time = h > 12 ? h - 12 + ":" + m + " PM" : h + ":" + m + " AM";
}
//var time = h > 12 ? h - 12 + ":" + m + " PM" : h + ":" + m + " AM";
console.log(`CURRENT TIME IS ${time}`);
This will work for everytime,
function Timer() {
var dt = new Date()
if (dt.getHours() >= 12){
ampm = "PM";
} else {
ampm = "AM";
}
if (dt.getHours() < 10) {
hour = "0" + dt.getHours();
} else {
hour = dt.getHours();
}
if (dt.getMinutes() < 10) {
minute = "0" + dt.getMinutes();
} else {
minute = dt.getMinutes();
}
if (dt.getSeconds() < 10) {
second = "0" + dt.getSeconds();
} else {
second = dt.getSeconds();
}
if (dt.getHours() > 12) {
hour = dt.getHours() - 12;
} else {
hour = dt.getHours();
}
if (hour < 10) {
hour = "0" + hour;
} else {
hour = hour;
}
document.getElementById('time').innerHTML = hour + ":" + minute + ":" + second + " " + ampm;
setTimeout("Timer()", 1000);
}
Timer()
<div id="time"></div>

add one day to date if it exceeded to a specific time in javascript

Here's my code for getting the time after adding specific time.. I don't know how to shift to tomorrow's date if the base_time is example: 4:50 PM and the 'default END TIME' is only 5:00 PM and I have to add 30 mins on the base_time. If I add 30 mins on the base, the final date/time is TOMORROW at 8:20 AM.. because the start of the day(work) is 8:00 AM.
Question : How to do this? e.g. January 3, 2016 04:50:00 PM + (00:30:00) = January 4, 2016 08:20:00 AM.
start time of work is at 8:00 AM
end is at 5:00 PM
Please help me on this. Thank you guys. I really need this.
var time = "";
var total_seconds = 0;
var total_time = 0;
// ===================================================================
function toSeconds(timeToConvert){
var hms = timeToConvert;
var a = hms.split(':');
seconds = (+a[0]) * 60 * 60 + (+a[1]) * 60 + (+a[2]);
total_seconds += seconds;
}
$('#btn').click(function () {
var d = new Date();
var month = d.getMonth();
var day = d.getDate();
var year = d.getFullYear();
var hr = d.getHours();
var min = d.getMinutes();
var sec = d.getSeconds();
if (sec <= 9) {
sec = ('0' + sec);
}
if (min <= 9) {
min = ('0' + min);
}
if (hr <= 9) {
hr = ('0' + hr);
}
var base_time = hr + ":" + min + ":" + sec;
toSeconds(base_time);
// toSeconds("16:30:00");
if ($('#acc1').is(":checked")) {
time = "00:15:00";
toSeconds(time);
}
if ($('#acc2').is(":checked")) {
time = "00:30:00";
toSeconds(time);
}
alert("total seconds = " + total_seconds);
total_time = total_seconds;
total_seconds = 0;
if (total_time <= 61200) {
var date = new Date(null);
date.setSeconds(total_time);
var date1 = day + "-" + (month+1) + "-" + year + " " + date.toISOString().substr(11, 8);
}
else {
var da = new Date();
var day1 = Number(da.toISOString().substr(8, 2)) + 1; // Date1=currentday+1
var month1 = da.getMonth();
var year1 = da.getFullYear();
total_time -= 61200;
var new_time = 28800 + total_time; // Morning 8'o clock + remaining time
da.setSeconds(total_time);
var date1 = day1 + "-" + (month1+1) + "-" + year1 + " " + da.toISOString().substr(11, 8);
}
alert(date1);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<label><input id="acc1" type="checkbox" name="acc">acc 1</label><br>
<label><input id="acc2" type="checkbox" name="acc">acc 2</label><br>
<input type="button" class="btn btn-success" id="btn" name="btn" value="button">
edited and modified based on #Navaneethan answer. thank for that. But no I'm curious on how to consider the weekends? Those days without work. For example, Friday, the next day should be on Monday. The same for the changes in Months. How am I supposed to do that. Please help me. Thank you.
I just modified your code... Try this. It may work
var time = "";
var total_seconds = 0;
var total_time = 0;
// ===================================================================
function toSeconds(timeToConvert) {
var hms = timeToConvert;
var a = hms.split(':');
var seconds = (+a[0]) * 60 * 60 + (+a[1]) * 60 + (+a[2]);
total_seconds += seconds;
}
$('#btn').click(function () {
var d = new Date();
var hr = d.getHours();
var min = d.getMinutes();
var sec = d.getSeconds();
if (sec <= 9) {
sec = ('0' + sec);
}
if (min <= 9) {
min = ('0' + min);
}
if (hr <= 9) {
hr = ('0' + hr);
}
var base_time = hr + ":" + min + ":" + sec;
toSeconds(base_time);
if ($('#acc1').is(":checked")) {
time = "00:15:00";
toSeconds(time);
}
if ($('#acc2').is(":checked")) {
time = "00:30:00";
toSeconds(time);
}
alert(total_seconds);
total_time = total_seconds;
total_seconds = 0;
var date = new Date();
if (total_time <= 61200) {
date.setSeconds(total_time);
var date1 = date.toISOString().substr(11, 8);
}
else {
var day1 = Number(date.toISOString().substr(8, 2)) + 1; // Date1=currentday+1
var month1 = date.getMonth();
var year1 = date.getFullYear();
total_time -= 61200;
var new_time = 28880 + total_time; //Morning 8'o clock + remaining time
date.setSeconds(total_time);
var date1 = day1 + "-" + month1 + "-" + year1 + ":" + date.toISOString().substr(11, 8);
}
alert(date1);
});

Clock and date javascript

Im creating a JS clock/date. I previously got the time to work perfectly then I decided to add more onto my clock (date). Right now I cant figure why it isn't working. If anyone could give me tip or idea how to fix it, I would greatly appreciate it.
function timedate()
{
var currentTime = new Date();
var hours = currentTime.getHours();
var minutes = currentTime.getMinutes();
var dn="PM"
var d = currentTime.getDate(); <--
var day = (d < 10) ? '0' + d : d;
var m = currentTime.getMonth() + 1; <--
var month = (m < 10) ? '0' + m : m;
var yy = currentTime.getYear(); <--
var year = (yy < 1000) ? yy + 1900 : yy;
if (hours<12)
{
dn="AM"
}
if (hours>12)
{
hours=hours-12
}
if (hours==0)
{
hours=12
}
if (minutes<=9)
{
minutes="0"+minutes
}
var clocklocation = document.getElementById('timedate');
clocklocation.innerHTML = "" +hours+":"+minutes+dn+""+day + "/" + month + "/" + year;
setTimeout("timedate()", 1000);
}
timedate();
Your code works, it is just not visible because you do not have seconds showing
Also change
setTimeout("timedate()", 1000);
to
setTimeout(timedate, 1000);
because it is not recommended
and remove the <--
Make sure it runs onload or after the tag you want to show it in
Alternatively remove the line and change
timedate();
to
setInterval(timedate,1000)
const pad = num => ("0" + num).slice(-2);
const timedate = () => {
const currentTime = new Date();
let hours = currentTime.getHours();
const minutes = pad(currentTime.getMinutes());
const seconds = pad(currentTime.getSeconds());
const d = currentTime.getDate();
const day = pad(d);
const month = pad(currentTime.getMonth() + 1);
const yy = currentTime.getFullYear();
let dn = "PM"
if (hours <= 12) dn = "AM";
if (hours >= 12) hours -= 12;
if (hours == 0) hours = 12;
hours = pad(hours);
document.getElementById('timedate').innerHTML = "" +
hours + ":" +
minutes + ":" +
seconds + dn + " " +
day + "/" + month + "/" + yy;
}
window.addEventListener("load", function() {
setInterval(timedate, 1000);
});
<span id="timedate"></span>
If you set the timeout with setTimeout(timedate, 1000) instead of your current magic string version, it works1.
1 I took the liberty of adding seconds to your code as well, to make it obvious that the clock updates. Of course, you also need to remove <-- from your code.

How to make Javascript time automatically update

I am using the following Javascript code to display the time on my website. How can I make this update automatically.
Thanks
<section class="portlet grid_6 leading">
<header>
<h2>Time<span id="time_span"></span></h2>
</header>
<script type="text/javascript">
var currentTime = new Date()
var hours = currentTime.getHours()
var minutes = currentTime.getMinutes()
if (minutes < 10){
minutes = "0" + minutes
}
var t_str = hours + ":" + minutes + " ";
if(hours > 11){
t_str += "PM";
} else {
t_str += "AM";
}
document.getElementById('time_span').innerHTML = t_str;
</script>
</section>
Use setTimeout(..) to call a function after a specific time. In this specific case, it is better to use setInterval(..)
function updateTime(){
var currentTime = new Date()
var hours = currentTime.getHours()
var minutes = currentTime.getMinutes()
if (minutes < 10){
minutes = "0" + minutes
}
var t_str = hours + ":" + minutes + " ";
if(hours > 11){
t_str += "PM";
} else {
t_str += "AM";
}
document.getElementById('time_span').innerHTML = t_str;
}
setInterval(updateTime, 1000);
Add all your javascript code in a function called updateClock() placed in the <head> section of your page, and alter the <body> tag that way:
<body onload="updateClock(); setInterval('updateClock()', 1000 )">
It will recalculate and redisplay the time every second. Since you only display hours and minutes, you can use a longer interval. If you want to update time every numSeconds you should use something like
<body onload="updateClock(); setInterval('updateClock()', numSeconds * 1000 )">
And of course, this one is just one of many gazillions solutions that you can find out there.
There are plenty of clock libraries out there. Perhaps check out this previous post: How to create a jquery clock timer
try this, a tidier version:
var el = document.getElementById('time_span')
setInterval(function() {
var currentTime = new Date(),
hours = currentTime.getHours(),
minutes = currentTime.getMinutes(),
ampm = hours > 11 ? 'PM' : 'AM';
hours += hours < 10 ? '0' : '';
minutes += minutes < 10 ? '0' : '';
el.innerHTML = hours + ":" + minutes + " " + ampm;
}, 1000);
GetTime();
function GetTime(){
var CurrentTime = new Date()
var hour = CurrentTime.getHours()
var minute = CurrentTime.getMinutes()
var second = CurrentTime.getSeconds()
if(minute < 10){
minute = "0" + minute
}
if(second < 10){
second = "0" + second
}
var GetCurrentTime = hour + ":" + minute + ":" + second + " ";
if(hour > 11){
GetCurrentTime += "p.m."
}else{
GetCurrentTime += "a.m."
}
document.getElementById("CurrentTime").innerHTML = GetCurrentTime;
setTimeout(GetTime,1000)
}
<span id="CurrentTime"></span>
A bit less messy would be:
timer();
function timer(){
var now = new Date,
hours = now.getHours(),
ampm = hours<12 ? ' AM' : ' PM',
minutes = now.getMinutes(),
seconds = now.getSeconds(),
t_str = [hours-12, //otherwise: what's the use of AM/PM?
(minutes < 10 ? "0" + minutes : minutes),
(seconds < 10 ? "0" + seconds : seconds)]
.join(':') + ampm;
document.getElementById('time_span').innerHTML = t_str;
setTimeout(timer,1000);
}
The timer updates (roughly) every second (= 1000 Ms), using setTimeout from within the timer function.
​See it in action
This code output format->00:00:00 and refresh automatically like real time clock, hope it works..
function r(txt) {
document.write(tex);
}
function createTIME() {
d = new Date();
var time = addZERO(d.getHours()) + ':' + addZERO(d.getMinutes()) + ':' + addZERO(d.getSeconds());
return 'Present Time = ' + time;
}
function doDyn() {
document.getElementById('Dyn').innerHTML = createTIME();
}
function addZERO(val) {
return ((val < 10) ? '0' : '') + val;
}
GetTime();
function GetTime(){
var CurrentTime = new Date()
var hour = CurrentTime.getHours()
var minute = CurrentTime.getMinutes()
var second = CurrentTime.getSeconds()
if(minute < 10){
minute = "0" + minute
}
if(second < 10){
second = "0" + second
}
var GetCurrentTime = hour + ":" + minute + ":" + second + " ";
if(hour > 11){
GetCurrentTime += "p.m."
}else{
GetCurrentTime += "a.m."
}
<!-- Try changing innerHTML to document.getElementById("CurrentTime").value -->
document.getElementById("CurrentTime").value = GetCurrentTime;
setTimeout(GetTime,1000)
}
<span id="CurrentTime"></span>
timer();
function timer(){
var currentTime = new Date()
var hours = currentTime.getHours()
var minutes = currentTime.getMinutes()
var sec = currentTime.getSeconds()
if (minutes < 10){
minutes = "0" + minutes
}
if (sec < 10){
sec = "0" + sec
}
var t_str = hours + ":" + minutes + ":" + sec + " ";
if(hours > 11){
t_str += "PM";
} else {
t_str += "AM";
}
document.getElementById('time_span').innerHTML = t_str;
setTimeout(timer,1000);
}
<header>
<h2>Time<span id="time_span"></span></h2>
</header>

Categories

Resources