.js help with the Date object and if/else - javascript

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
}

Related

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.

Adding "0" if clock have one digit

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}`;

Javascript clock based on custom time

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);​

convert time string format

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";
}

Time conversion from 24hrs to 12hrs

I am getting the time like 13.40, but i need to convert it to 1.40.. any one know, what is the best way to do this. i am using jquery to make time.
my code is :
var time = new Date(myDate);
var hours = time.getHours();
alert(hours);
if (hours > 12) {
hours -= 12;
}
Um, as simple as that.
Use the modulus operator, % for this
var input = "13.40";
var atoms = input.split(".");
var output = atoms[0] % 12 + "." + atoms[1];
output; // "1.40";
If you want to prefix with 0 then you can do this
var output = ("0" + atoms[0] % 12).slice(-2) + "." + atoms[1];
output; // "01.40";
If you want AM/PM as a suffix
var output = ("0" + atoms[0] % 12).slice(-2) + "." + atoms[1] +
(atoms[0] < 13 ? " AM" : " PM");
output; // "01.40 PM";
Try
hours = hours > 12 ? hours - 12 : hours;
You can use the modulo operator for this:
var hours = time.getHours() % 12

Categories

Resources