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.
Related
This question already has answers here:
Fire event at a certain time of the day
(4 answers)
Closed 11 months ago.
im a noob in js xd, i want to put a text in an html in a choosen time of a clock!
i want it to print "make a wish" when its 11:11
the code:
function startTime() {
const today = new Date();
let h = today.getHours();
let m = today.getMinutes();
let s = today.getSeconds();
m = checkTime(m);
s = checkTime(s);
document.getElementById('txt').innerHTML = h + ":" + m + ":" + s;
setTimeout(startTime, 1000);
}
function checkTime(i) {
if (i < 10) {i = "0" + i}; // add zero in front of numbers < 10
return i;
}
This can be done via setInterval in javascript with some basic if condition checks.
First create a date object via new Date() then get hours and minutes, check if the hour and minute is equal to your specified time then print the value.
We need to set an interval of 60 seconds which is equal to 60,000 milliseconds to not print again the same value in that minute.
You can try this -
setInterval(function(){
var date = new Date();
if(date.getHours() === 11 && date.getMinutes() === 11){
console.log("make a wish");
}
}, 60000);
Something like this will do.
function startTime() {
const today = new Date();
let h = today.getHours();
let m = today.getMinutes();
let s = today.getSeconds();
m = checkTime(m);
s = checkTime(s);
document.getElementById('txt').innerHTML = h + ":" + m + ":" + s;
if (h == 11 && m == 11) {
console.log("Make a wish");
} else {
setTimeout(startTime, 1000);
}
}
function checkTime(i) {
if (i < 10) { i = "0" + i }; // add zero in front of numbers < 10
return i;
}
startTime();
<p id="txt"></p>
Use the callback function from SetInterval and get currentt time. afterwards you can check if it 11:11. If successful dont forget to clear the intervall.
const innterval = setInterval(function () {
check()
}, 5000);
function check() {
var today = new Date();
var t1111 = today.getHours() + ':' + today.getMinutes();
if (t1111 === '11:11') {
alert('11:11')
document.getElementById('txt').innerHTML = t111 + ' PARTY!'
clearInterval(innterval);
}
console.log('Current time: ' + t1111 + ' still Waiting')
}
<div id="txt"></div>
I've been given some JavaScript that creates a digital clock to go onto a webpage. This is working perfectly, however, I'm trying to amend it to wrap the am/pm suffix (or Diem in this code) in span or bold tags so that I can style it differently to the rest of the time in the CSS.
I'm sure this would be really simple for someone that knows what they're doing but I'm really struggling.
Any help would be appreciated, the JavaScript is below:
function renderTime() {
var currentTime = new Date();
var diem = "AM";
var h = currentTime.getHours();
var m = currentTime.getMinutes();
var s = currentTime.getSeconds();
setTimeout('renderTime()',1000);
if (h == 0) {
h = 12;
} else if (h > 12) {
h = h - 12;
diem="PM";
}
if (m < 10) {
m = "0" + m;
}
if (s < 10) {
s = "0" + s;
}
var myClock = document.getElementById('clockDisplay');
myClock.textContent = h + ":" + m + " " + diem;
myClock.innerText = h + ":" + m + " " + diem;
var diem = document.createElement('span');
}
renderTime();
So, I want to do the same thing, but in a URL style, like this: http://example.com/example?h="10"&m="42"
Just concatenate the hour and minute to the URL prefix and return that as a string.
Also, your code produces the wrong diem for times between noon and 12:59, since those should be 12PM.
function getTimeURL() {
var currentTime = new Date();
var diem = "AM";
var h = currentTime.getHours();
var m = currentTime.getMinutes();
var s = currentTime.getSeconds();
if (h == 0) {
h = 12;
} else if (h > 12) {
h = h - 12;
diem="PM";
} else {
diem = "PM";
}
if (m < 10) {
m = "0" + m;
}
var url = `http://example.com/example?h=${h}${diem}&m=${m}`;
return url;
}
console.log(getTimeURL());
I added a bunch of comments to your code that'll hopefully make it easier to understand. I also added a global variable that will store your linkText value as it's changed by the function.
// create a global variable that stores our text for the link.
// Your renderTime() function will update it every second.
var linkText = "";
function renderTime() {
//grab the new date
var currentTime = new Date();
//set diem (whatever that means) to "AM"
var diem = "AM";
//get the hours from our current time
var h = currentTime.getHours();
//get the minutes
var m = currentTime.getMinutes();
//get the seconds
var s = currentTime.getSeconds();
//run this function every 1000 milliseconds
setTimeout('renderTime()', 1000);
//if the hour is 0, set it to twelve instead
if (h == 0) {
h = 12;
//else if the hour is any number higher than 12,
//subtract 12 from its value and change diem to "PM"
} else if (h > 12) {
h = h - 12;
diem = "PM";
}
//if the minutes are 0-9 add a 0 before.
if (m < 10) {
m = "0" + m;
}
//if the seconds are 0-9 add a 0 before.
if (s < 10) {
s = "0" + s;
}
//get our clock element
var myClock = document.getElementById('clockDisplay');
//populate our clock element
myClock.textContent = h + ":" + m + ":" + s + " " + diem;
myClock.innerText = h + ":" + m + ":" + s + " " + diem;
//not sure why you're writing over your AM/PM variable at the end here,
//so I commented it out
//var diem = document.createElement('span');
//set our linkText value to be the current hour and minute
linkText = 'http://example.com/example?h="' + h + '"&m="' + m + '"';
}
//run that thang!
renderTime();
<div id="clockDisplay"></div>
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 have a Rails app where I'm displaying a realtime clock in my application layout. I'm using this code to make it work:
<div id="time" class="time_display"></div>
<script type="text/javascript">
function checkTime(i) {
if (i < 10) {
i = "0" + i;
}
return i;
}
function startTime() {
var today = new Date();
var h = today.getHours();
var m = today.getMinutes();
var s = today.getSeconds();
// add a zero in front of numbers<10
m = checkTime(m);
s = checkTime(s);
document.getElementById('time').innerHTML = h + ":" + m + ":" + s;
t = setTimeout(function () {
startTime()
}, 500);
}
startTime();
</script>
What I'd like to be able to do is somehow give the user the option to switch between a realtime clock in military time and regular AM/PM time with the AM/PM included but clicking on the div.
I've done some searching but haven't found anything that works too well. I'm open to any solutions someone might have be it JS or jQuery.
Any help would be greatly appreciated. If my question is not clear, please let me know.
Here is code. It get updated only on next tick, but you can manage to fix that if you want
function checkTime(i) {
if (i < 10) {
i = "0" + i;
}
return i;
}
function startTime() {
var today = new Date();
var h = today.getHours();
var m = today.getMinutes();
var s = today.getSeconds();
var ampm = h >= 12 ? 'pm' : 'am';
// add a zero in front of numbers<10
m = checkTime(m);
s = checkTime(s);
var timer = document.getElementById('time');
if (timer.type == 'r') {
h = h % 12;
h = h ? h : 12;
timer.innerHTML = h + ":" + m + ":" + s + " " + ampm;
} else
timer.innerHTML = h + ":" + m + ":" + s;
t = setTimeout(function () {
startTime()
}, 500);
document.getElementById('time').onclick = function () {
if (this.type == 'r')
this.type = 'm';
else
this.type = 'r';
}
}
startTime();
<div id="time" class="time_display"></div>
Really:
var ampm = 'am';
if(hours > 11){
ampm = 'pm';
if(hours > 12)hours = hours-12;
}
if(hours === 0)hours = 12;
Also, you could do something like:
today.toLocaleString().split(',')[1];
I need to know the percentage remaining between two dates.
I've used this code:
$(function () {
var end = $('#data').text();
var formattedDate = new Date();
var day = formattedDate.getDate();
var month = formattedDate.getMonth();
month += 1;
var year = formattedDate.getFullYear();
if (day < 10) {
day = "0" + day;
}
if (month < 10) {
month = "0" + month;
}
var today = day + "/" + month + "/" + year;
remaining = Math.round(((end - today) * 100) / today));
alert(remaining);
});
But it does'nt work.
Any suggestion?
Thanks
You're subtracting two strings, which is why it won't work.
Subtract two Date objects instead, and you'll get the milliseconds between them (ignoring the maths as to what you define as a % of 2 dates).
var now = new Date();
var then = new Date($('#data').text());
var remaining = Math.round(((then - now) * 100) / now);
You can still, of course, get your formatted string of DD/MM/YY via;
var formattedDays = (now.getDay() < 10 ? "0" : "") + now.getDay();
var formattedMonth = (now.getMonth() < 9 ? "0" : "") + (now.getMonth() + 1);
var formattedDate = formattedDays + "/" + formattedMonth + "/" + now.getFullYear();
Note that you have an extra closing parenthesis at the end of your Math.round() line as well.