i have some clock script. Everything is fine and it's work perfectly but... i have one problem. If at the clock is set one digit hour or minute like 1:5 clock not adding "0" digit before. This what i'v done but it does't work. Can u help me, much thx?
window.setInterval(function update_clock() {
var currentTime = new Date();
var currentHours = currentTime.getHours();
var currentMinutes = currentTime.getMinutes();
$.ajax({
success: function (clock) {
document.getElementById("hour").firstChild.nodeValue = currentHours;
document.getElementById("minutes").firstChild.nodeValue = currentMinutes;
if (currentMinutes.length == 1) {
currentMinutes = "0" + currentMinutes;
}
}
});
}, 999);
You may use .slice to extract a portion of a string. Pass a negative number to it, in order to slice from the end of the string.
Therefore, the following is possible, and quite simple:
('0'+currentMinutes).slice(-2)
Concatenating with '0' makes sure that the target of the operation will always be a string. ('0'+currentMinutes) will yield a 2 or 3 letter string ("07" or "017", for instance). Slicing the last two characters off that string will give you a 0-padded two-digit number.
Note that the above would yield "00" if currentMinutes is 100, so it assumes that you know the values you'll be working with.
This could be extracted to something more reusable:
Number.prototype.zeroPad = function() {
return ('0'+this).slice(-2);
};
That would allow you to write:
currentMinutes.zeroPad();
You could also make the length of the padding variable:
Number.prototype.zeroPad = function(length) {
length = length || 2; // defaults to 2 if no parameter is passed
return (new Array(length).join('0')+this).slice(length*-1);
};
Which could be called as:
currentMinutes.zeroPad(); // e.g. "07" or "17"
currentMinutes.zeroPad(3); // e.g. "007" or "017"
Note that while currentMinutes.zeroPad() will work, 7.zeroPad() would not.
currentMinutes is a number, so it does not have the length property. Also, you must check the length before set the currentMinutes to the minutes element.
Something like:
var currentHours = currentTime.getHours();
var currentMinutes = currentTime.getMinutes();
$.ajax({
success: function (clock) {
if (currentMinutes.toString().length == 1) {
currentMinutes = "0" + currentMinutes;
}
document.getElementById("hour").firstChild.nodeValue = currentHours;
document.getElementById("minutes").firstChild.nodeValue = currentMinutes;
}
});
Try using the padStart() method. Based on MDN docs, the padStart() method keeps padding the string with another string until it reaches the desired length. Link to MDN docs on padStart().
If you want to format your string to have 4 digits with leading zeros if less than 4 digits are available. The padStart() method can come to the rescue as follows:
let str = "34"
str = str.padStart(4, "0") // results in "0034"
console.log(str)
An example of the date case:
var now = new Date();
var year= now.getFullYear();
var month= (now.getMonth()+1).toString().padStart(2, "0");
var day= now.getDate().toString().padStart(2, "0");
var hour = now.getHours().toString().padStart(2, "0");
var minute = now.getMinutes().toString().padStart(2, "0");
document.getElementById("date").innerHTML =`${day}-${month}-${year}-${hour}:${minute}`;
<div id="date"></div>
currentMinutes won't have a length property, as it's a Number, not a String.
You could force it to be a String.
if ((currentMinutes+'').length == 1) {
currentMinutes = "0" + currentMinutes;
}
But, because you have a Number, you should make your condition...
if (currentMinutes < 10) {
currentMinutes = "0" + currentMinutes;
}
If you were especially crazy, you could do...
var hoursMinutes = ((new Date)+"").match(/\d+:\d+(?=:)/)[0].split(":");
You could also check sprintf() for javascript.
You could go with something as simple as:
sprintf("%02d:%02d", currentHours, currentMinutes);
Using functions that accept formatting lets you have much more control over your output, when you need to.
in android(build in)
String time=String.format("%02d:%02d",hourOfDay,minute);
in javascript use (sprintf.js)
int i = 1;
string s = sprintf("%02d", i);
document.write(s); // Prints "01"
sprintf.js:
http://www.diveintojavascript.com/projects/javascript-sprintf
Based on the other awnsers, I created this lines of code:
var now = new Date();
var dd = now.getDate();
var mm = now.getMonth()+1;
var y = now.getFullYear();
var h = now.getHours();
var m = now.getMinutes();
function aZero(n) {
return n.toString().length == 1 ? n = '0' + n: n;
}
document.getElementById("out").innerHTML =
aZero(dd) + "-" +
aZero(mm) + "-" +
y + " - " +
aZero(h) + ":" +
aZero(m);
<div id="out">my time :D</div>
Cu next time.
Try use ('0' + currentTime.getHours()).slice(-2)
Updated your Question -
window.setInterval(function update_clock() {
var currentTime = new Date();
var currentHours = ('0' + currentTime.getHours()).slice(-2);
var currentMinutes = ('0' + currentTime.getMinutes()).slice(-2);
$.ajax({
success: function (clock) {
document.getElementById("hour").firstChild.nodeValue = currentHours;
document.getElementById("minutes").firstChild.nodeValue = currentMinutes;
if (currentMinutes.length == 1) {
currentMinutes = "0" + currentMinutes;
}
}
});
}, 999);
You could do based on length.
My solution will be
var mnt = '' + (seconds / 60).toFixed();
if (mnt.toString().length == 1) mnt = '0' + mnt;
var sec = '' + (seconds % 60).toFixed();
if (sec.toString().length == 1) sec = '0' + sec;
return `${mnt}:${sec}`;
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>
This is what have tried:
partly pseudocode:
var hours = date1.getHours();
var minutes = date2.getMinutes();
if (hours.length == 1)
hours = "0" + hours;
if (minutes.length == 1)
minutes = "0" + minutes;
var time = hours + ':' + minutes;
Is there a smarter way like a formatted string function where I can say:
var minutes = date.getMinutes('mm');
var hours = date.getHours('hh');
so it adds the zeros automatically ?
Here is your code fixed since there is no length on an integer
var hours = date1.getHours();
var minutes = date2.getMinutes();
if (hours<10) hours = "0" + hours;
if (minutes<10) minutes = "0" + minutes;
var time = ""+ hours + ":" + minutes;
You do not need a framework and there is no shorter way to do this
This may be what you mean:
Live demo
function pad(num) {
return ("0"+num).slice(-2)
}
var time = pad(date1.getHours())+":"+pad(date2.getMinutes());
This functionality doesn't exist natively in javascript, you have to either add it yourself (as you have started to do), or, use a package.
moment
Mozilla has an example
Here's a blog post to a date formatting function
Where can I find documentation on formatting a date in JavaScript?
How to format a JavaScript date
Use DateJS and you will be able to use mm and hh to add the preceding zeros :)
https://code.google.com/p/datejs/wiki/FormatSpecifiers
You can add a method to Number prototype
Number.prototype.pad0 = function(length) {
var result = this.toString();
while(result.length<length) result = "0"+result;
return result;
}
Then you can get what you want
var date = new Date();
console.log(date.getMinutes().pad0(2));
console.log(date.getHours().pad0(2));
Yet another way of doing it:
var d = new Date();
var t = [ d.getHours(), d.getMinutes(), d.getSeconds() ];
var s = t.map( function(z){return ('00'+z).slice(-2)} ).join(':');
console.log(s);
Time parts are put into an array. That array goes through map() where the numbers get leading zeros. The resulting array is then joined into a string with the ":" separator.
Convert numbers to strings before you check the lengths:
var hours = String(date1.getHours());
var minutes = String(date2.getMinutes());
if (hours.length == 1)
hours = "0" + hours;
if (minutes.length == 1)
minutes = "0" + minutes;
var time = hours + ':' + minutes;
I am using the following script below, and what I am trying to do is to set a custom time to the script and for it to auto update without the need to re-set the time each time. (I only want to set the time once and want my script to keep track of the time and display it)
When I run the script it displays: NaN:NaN:NaN AM
My Code is as follows:
<div id="js_clock"> display clock here </div>
<script language="javascript">
function js_clock(clock_time)
{
var clock_hours = clock_time.getHours();
var clock_minutes = clock_time.getMinutes();
var clock_seconds = clock_time.getSeconds();
var clock_suffix = "AM";
if (clock_hours > 11){
clock_suffix = "PM";
clock_hours = clock_hours - 12;
}
if (clock_hours == 0){
clock_hours = 12;
}
if (clock_hours < 10){
clock_hours = "0" + clock_hours;
}
if (clock_minutes < 10){
clock_minutes = "0" + clock_minutes;
}
if (clock_seconds < 10){
clock_seconds = "0" + clock_seconds;
}
var clock_div = document.getElementById('js_clock');
clock_div.innerHTML = clock_hours + ":" + clock_minutes + ":" + clock_seconds + " " + clock_suffix;
setTimeout("js_clock()", 1000);
}
var serverTime = new Date("09:20:50");
js_clock(serverTime);
</script>
You have a problem creating the date, new Date("09:20:50"); returns Invalid Date.
if you want to set hours minutes and seconds use
new Date(year, month, day [, hour, minute, second, millisecond ])
or take a look here.
Also you forgot to pass a date to the setTimeout, try:
setTimeout(function() {
js_clock(new Date(/*pass hours minutes and seconds here*/))
}, 1000);
I think you've forgotten passing an argument to js_clock(). Maybe you shoud do:
setTimeout(
function() {
//Call the function again updating seconds by 1
js_clock(
new Date(
clock_time.getFullYear(),
clock_time.getMonth(),
clock_time.getDate(),
clock_time.getHours(),
clock_time.getMinutes(),
clock_time.getSeconds() + 1
)
);
},
1000
);
EDIT:
I missed the point this can be done with a single function call:
setTimeout(
function() {
js_clock(new Date(+clock_time + 1000));
},
1000
);
The +clock_time statement converts the Date object to milliseconds from the UNIX Epoch, so updating the time is as simple as summing 1000 milliseconds.
Thanks to user RobG ;-)
Your code has some serious flaws, such as the following.
setTimeout doesn't run at exactly the interval set, but as soon as it can afterward so this clock will slowly drift, sometimes by a lot.
Passing a string to Date and expecting it to be correctly parsed is problematic. In ECMA-262 ed 3 it was entirely implementation dependent, in ES5 the string is required to be a custom version of the ISO8601 long format (but note that not all browsers in use support ES5).
Lastly, if the client is busy, the function may not run for several seconds so the clock needs to be based on the client clock, then ajusted for the time difference.
The following function does all the above.
<script type="text/javascript">
var customClock = (function() {
var timeDiff;
var timeout;
function addZ(n) {
return (n < 10? '0' : '') + n;
}
function formatTime(d) {
return addZ(d.getHours()) + ':' +
addZ(d.getMinutes()) + ':' +
addZ(d.getSeconds());
}
return function (s) {
var now = new Date();
var then;
// Set lag to just after next full second
var lag = 1015 - now.getMilliseconds();
// Get the time difference if first run
if (s) {
s = s.split(':');
then = new Date(now);
then.setHours(+s[0], +s[1], +s[2], 0);
timeDiff = now - then;
}
now = new Date(now - timeDiff);
document.getElementById('clock').innerHTML = formatTime(now);
timeout = setTimeout(customClock, lag);
}
}());
window.onload = function() {
customClock('09:20:50');
}
</script>
<div id="clock"></div>
WAIT! just realised, this is still not showing the correct time. The error is gone, but the time isn't what you are looking for.
window.js_clock = function js_clock(clock_time) {
var clock_hours = clock_time.getHours();
var clock_minutes = clock_time.getMinutes();
var clock_seconds = clock_time.getSeconds();
var clock_suffix = "AM";
if (clock_hours > 11) {
clock_suffix = "PM";
clock_hours = clock_hours - 12;
}
if (clock_hours === 0) {
clock_hours = 12;
}
if (clock_hours < 10) {
clock_hours = "0" + clock_hours;
}
if (clock_minutes < 10) {
clock_minutes = "0" + clock_minutes;
}
if (clock_seconds < 10) {
clock_seconds = "0" + clock_seconds;
}
var clock_div = document.getElementById('js_clock');
clock_div.innerHTML = clock_hours + ":" + clock_minutes + ":" + clock_seconds + " " + clock_suffix;
setTimeout("js_clock(new Date())", 1000);
}
var serverTime = new Date("09:20:50");
window.js_clock(serverTime);
I want to convert time data to the format HH:mm:ss in JavaScript.
I've got a problem in my code (see comments inside the code):
function parseTime(timeString){
var timeString = timeString.toLowerCase();
timeString = $.trim(timeString);
var regEx = /^([0-9]|1[0-9]|2[0-3])$/;
var regEx2 = /^([0-9]|1[0-9]|2[0-3])\.?([0-5][0-9])$/;
var regEx3 = /^([0-9]|1[0-2])(a|p|am|pm)$/;
var regEx4 = /^([1-9]|10|11|12)\.?([0-5][0-9])(a|p|am|pm)$/;
if(regEx.test(timeString)){
var hours = timeString;
if(hours.length == 1){
hours = '0' + hours;
}
return hours + ':00:00';
}
else if(regEx2.test(timeString)){
var hoursEndIndex, minutesStartIndex;
if(timeString.indexOf('.')){
hoursEndIndex = timeString.indexOf('.');
minutesStartIndex = timeString.indexOf('.') + 1;
}else if(timeString.length == 3){//Problem here timeString.length returns 3 but the code below isn't executed?
hoursEndIndex = 1;
minutesStartIndex = 1;
}else if(timeString.length == 4){//Same thing here?
hoursEndIndex = 2;
minutesStartIndex = 2;
return timeString.length;
}
var hours = timeString.substring(0, hoursEndIndex);
if(hours.length == 1){
hours = '0' + hours;
}
var minutes = timeString.substr(minutesStartIndex, 2);
return hours + ':' + minutes + ':00';
}
I think you are using indexOf incorrectly here:
if(timeString.indexOf('.')){
From the documentation:
Returns the first index at which a given element can be found in the array, or -1 if it is not present.
Probably you mean this:
if(timeString.indexOf('.') > -1) {
With your code the expression in the first if statement will be true even if the string does not contain a dot. This means that the else if statement will never be executed.
I want to convert a almost any kind of time format to the format HH:mm:ss in javacript
Check this out: http://www.datejs.com/
There's no reason to re-invent the wheel.
However, if you are required to implement this yourself, then I believe Mark's solution will help
You're using else if, which requires that all preceding conditional blocks equate to false.
Try this:
if(timeString.indexOf('.')){
hoursEndIndex = timeString.indexOf('.');
minutesStartIndex = timeString.indexOf('.') + 1;
}
if(timeString.length == 3){
hoursEndIndex = 1;
minutesStartIndex = 1;
} else if(timeString.length == 4){
hoursEndIndex = 2;
minutesStartIndex = 2;
return timeString.length;
}
Perhaps you should use captured groups instead of parsing the string again:
var groups = regEx2.exec(timeString);
if(groups){
var hours = groups[0];
if(hours.length == 1){
hours = '0' + hours;
}
var minutes = groups[1];
return hours + ":" + minutes + ":00";
}
ok so im trying to create something where certain elements change based on time of day. that time of day is gotten via system clock.
heres my code:
var currTime = new Date();
var currHrs = currTime.getHours();
var currMins = currTime.getMinutes();
var currSecs = currTime.getSeconds();
if (currMins < 10){
currMins = "0" + currMins;
}
var suffix = "AM";
if (currHrs >= 12) {
suffix = "PM";
currHrs = currHrs - 12;
}
if (currHrs == 0) {
currHrs = 12;
}
//display thr and minutes .
var myTime = currHrs + ":" + currMins;
if(myTime< 12){
document.getElementById("clock").innerHTML = myTime;
} else {
//code here
}
problem im having is that the time isnt being written at all in the html "clock" div.
i know it works because if i take out the 'if' and just do the document.write etc, its prints to screen.
im assuming that the problem is the myTime > 12 part. if i do '>' or '<' , it still doesnt work.
what i want is that say for example, if its before 12pm something happens, etc. i just dont know how to target for example, morning time from noon, night etc.
any ideas, etc ill gladly appreciate.
thanks in advanced.
Yes, your problem is your if condition, or perhaps what comes before it.
//display thr and minutes .
var myTime = currHrs + ":" + currMins;
You have created myTime as a string e.g. "12:30". Obviously this is not suitable for comparison with a number.
It won't work with currHrs either because, with your logic, that is never a number less than 12.
I suggest you map out in pseudo code what it is you are trying to accomplish, as it all seems a bit muddled up there.
You were close. I simply moved a few things around for you.
Edited: Made a few mistakes in my haste. And apologies for syntax error. Fixed now.
var currTime = new Date();
var currHrs = currTime.getHours();
var currMins = currTime.getMinutes();
var currSecs = currTime.getSeconds();
if (currMins < 10) {
currMins = "0" + currMins;
}
var suffix = "AM";
if (currHrs >= 12) {
suffix = "PM";
currHrs = currHrs - 12;
} else if (currHrs == 0) {
currHrs = 12;
}
var myTime = (currHrs == 0 ? 12 : currHrs) + ":" + currMins + " " + suffix;
if (myTime.match(/(AM)/)) {
document.getElementById("clock").innerHTML = myTime;
} else {
// code here
}
After this line myTime is a string
var myTime = currHrs + ":" + currMins;
You're doing a string comparison to an int below.
if(myTime< 12){
document.getElementById("clock").innerHTML = myTime;
} else {
//code here
}
Did you mean to do this ?
if(currHrs < 12){
document.getElementById("clock").innerHTML = myTime;
} else {
//code here
}