I am making a simple time calculator in javascript. I have converted the times into 12-hour instead of 24 hour time for simplicity, however the code I have for calculating am/pm always shows am. Any reason why this would be happening?
Here is my code:
function solveTime(x) {
var suffixSolve = (utcHours + x) % 24;
var suffix = "am";
if (utcHours > 12) {
var suffix = "pm";
}
if (utcMinutes == 0) {
utcMinutesLead = "00";
}
if (utcMinutes < 10) {
utcMinutesLead = "0" + utcMinutes;
}
var timeSolve = (((utcHours + x) + 11) % 12 + 1);
var timeTotal = timeSolve + ":" + utcMinutesLead + " " + suffix;
var utcMod = x;
if (utcMod > 0) {
utcMod = "+" + utcMod;
}
document.getElementById(x).innerHTML = "(UTC" + utcMod + ") " + timeTotal;
}
and here is the code behind utcHours
var masterTimeUTC = new Date();
var utcHours = masterTimeUTC.getUTCHours();
var utcMinutes = masterTimeUTC.getUTCMinutes();
var utcSeconds = masterTimeUTC.getUTCSeconds();
var utcMinutesLead = masterTimeUTC.getUTCMinutes();
Example here: http://codepen.io/markgamb/pen/gwGkbo
The issue is you should be checking whether suffixSolve is greater than 12 instead of utcHours, because utcHours does not change due to the value of x. Since you can shift the hours forward and backwards, I created a variable shift to handle that.
function solveTime(x) {
if (x < 0) {
var shift = 24 + x;
} else {
var shift = x;
}
var suffixSolve = (utcHours + shift) % 24;
var suffix = "am";
if (suffixSolve > 12) {
suffix = "pm";
}
if (utcMinutes == 0) {
utcMinutesLead = "00";
}
if (utcMinutes < 10) {
utcMinutesLead = "0" + utcMinutes;
}
var timeSolve = (((utcHours + x) + 11) % 12 + 1);
var timeTotal = timeSolve + ":" + utcMinutesLead + " " + suffix;
var utcMod = x;
if (utcMod > 0) {
utcMod = "+" + utcMod;
}
document.getElementById(x).innerHTML = "(UTC" + utcMod + ") " + timeTotal;
}
var masterTimeUTC = new Date();
var utcHours = masterTimeUTC.getUTCHours();
var utcMinutes = masterTimeUTC.getUTCMinutes();
var utcSeconds = masterTimeUTC.getUTCSeconds();
var utcMinutesLead = masterTimeUTC.getUTCMinutes();
solveTime(4);
solveTime(0);
solveTime(-8);
<div id="4"></div>
<div id="-8"></div>
<div id="0"></div>
Related
This question already has answers here:
Why does Date.parse give incorrect results?
(11 answers)
Closed 3 years ago.
I wrote the following code for displaying a different image depending on the date (right now this example just console logs a message). The code works fine in Chrome and Firefox on Mac, but does not work correctly or give any errors on Safari (in Safari the message does not change depending on the date, it just says the same). How is Safari processing this differently? How can I get this to work on Safari with minimal changes?
Here's a working repl.
Here's the code:
/* change these dates */
var ddt = new Date("2019, 8, 22");
var pre = new Date("2019, 8, 23");
var ton = new Date("2019, 8, 26");
var post = new Date("2019, 8, 27");
// todays date
var currDate = new Date();
var mm = currDate.getMonth() + 1;
var dd = currDate.getDate();
var yyyy = currDate.getFullYear();
// Get the date parts
var ddtDay = ddt.getDate();
var ddtMonth = ddt.getMonth() + 1;
var ddtYear = ddt.getFullYear();
//console.log(ddtYear, ddtMonth, ddtDay);
var preDay = pre.getDate();
var preMonth = pre.getMonth() + 1;
var preYear = pre.getFullYear();
//console.log(preYear, preMonth, preDay);
var tonDay = ton.getDate();
var tonMonth = ton.getMonth() + 1;
var tonYear = ton.getFullYear();
//console.log(tonYear, tonMonth, tonDay);
var postDay = post.getDate();
var postMonth = post.getMonth() + 1;
var postYear = post.getFullYear();
//console.log(postYear, postMonth, postDay);
// format the date parts
if (ddtDay < 10) {
ddtDay = '0' + ddtDay;
}
if (ddtMonth < 10) {
ddtMonth = '0' + ddtMonth;
}
if (preDay < 10) {
preDay = '0' + preDay;
}
if (preMonth < 10) {
preMonth = '0' + preMonth;
}
if (tonDay < 10) {
tonDay = '0' + tonDay;
}
if (tonMonth < 10) {
tonMonth = '0' + tonMonth;
}
if (postDay < 10) {
postDay = '0' + postDay;
}
if (tonMonth < 10) {
postMonth = '0' + postMonth;
}
if (dd < 10) {
dd = '0' + dd;
}
if (mm < 10) {
mm = '0' + mm;
}
var ddtF = (ddtYear + '-' + ddtMonth + '-' + ddtDay);
var preF = (preYear + '-' + preMonth + '-' + preDay);
var tonF = (tonYear + '-' + tonMonth + '-' + tonDay);
var postF = (postYear + '-' + postMonth + '-' + postDay);
var today = (yyyy + '-' + mm + '-' + dd);
console.log(ddtF);
console.log(preF);
console.log(tonF);
console.log(postF);
console.log(today);
// logic
if (today >= postF) {
console.log('post');
} else if (today === tonF) {
console.log('ton');
} else if (today < tonF && today >= preF) {
console.log('pre');
} else if (today <= ddtF) {
console.log('ddt');
}
"2019, 8, 22" is not a portable date format. The Date constructor has a portable calling sequence where you give each component of the date as a separate argument, so use
var ddt = new Date(2019, 7, 22);
and similarly for all the other variables.
And remember that months are counted from 0 in JavaScript, so you need to subtract 1 from the month argument (August is 7).
/* change these dates */
var ddt = new Date(2019, 7, 22);
var pre = new Date(2019, 7, 23);
var ton = new Date(2019, 7, 26);
var post = new Date(2019, 7, 27);
// todays date
var currDate = new Date();
var mm = currDate.getMonth() + 1;
var dd = currDate.getDate();
var yyyy = currDate.getFullYear();
// Get the date parts
var ddtDay = ddt.getDate();
var ddtMonth = ddt.getMonth() + 1;
var ddtYear = ddt.getFullYear();
//console.log(ddtYear, ddtMonth, ddtDay);
var preDay = pre.getDate();
var preMonth = pre.getMonth() + 1;
var preYear = pre.getFullYear();
//console.log(preYear, preMonth, preDay);
var tonDay = ton.getDate();
var tonMonth = ton.getMonth() + 1;
var tonYear = ton.getFullYear();
//console.log(tonYear, tonMonth, tonDay);
var postDay = post.getDate();
var postMonth = post.getMonth() + 1;
var postYear = post.getFullYear();
//console.log(postYear, postMonth, postDay);
// format the date parts
if (ddtDay < 10) {
ddtDay = '0' + ddtDay;
}
if (ddtMonth < 10) {
ddtMonth = '0' + ddtMonth;
}
if (preDay < 10) {
preDay = '0' + preDay;
}
if (preMonth < 10) {
preMonth = '0' + preMonth;
}
if (tonDay < 10) {
tonDay = '0' + tonDay;
}
if (tonMonth < 10) {
tonMonth = '0' + tonMonth;
}
if (postDay < 10) {
postDay = '0' + postDay;
}
if (tonMonth < 10) {
postMonth = '0' + postMonth;
}
if (dd < 10) {
dd = '0' + dd;
}
if (mm < 10) {
mm = '0' + mm;
}
var ddtF = (ddtYear + '-' + ddtMonth + '-' + ddtDay);
var preF = (preYear + '-' + preMonth + '-' + preDay);
var tonF = (tonYear + '-' + tonMonth + '-' + tonDay);
var postF = (postYear + '-' + postMonth + '-' + postDay);
var today = (yyyy + '-' + mm + '-' + dd);
console.log(ddtF);
console.log(preF);
console.log(tonF);
console.log(postF);
console.log(today);
// logic
if (today >= postF) {
console.log('post');
} else if (today === tonF) {
console.log('ton');
} else if (today < tonF && today >= preF) {
console.log('pre');
} else if (today <= ddtF) {
console.log('ddt');
}
I get javascript codes for Hijri+Gregorian date. I want to put Hijri date first and next Gregorian like this:
Senin, 2 Januari 2017 M / 3 Rabiul Tsani 1438 H
to
Senin, 3 Rabiul Tsani 1438 H / 2 Januari 2017 M
Please help me, because i can't edit javascript codes.
This is the codes:
var fixd;
function isGregLeapYear(year) {
return year%4 == 0 && year%100 != 0 || year%400 == 0;
}
function gregToFixed(year, month, day) {
var a = Math.floor((year - 1) / 4);
var b = Math.floor((year - 1) / 100);
var c = Math.floor((year - 1) / 400);
var d = Math.floor((367 * month - 362) / 12);
if (month <= 2)
e = 0;
else if (month > 2 && isGregLeapYear(year))
e = -1;
else
e = -2;
return 1 - 1 + 365 * (year - 1) + a - b + c + d + e + day;
}
function Hijri(year, month, day) {
this.year = year;
this.month = month;
this.day = day;
this.toFixed = hijriToFixed;
this.toString = hijriToString;
}
function hijriToFixed() {
return this.day + Math.ceil(29.5 * (this.month - 1)) + (this.year - 1) * 354 + Math.floor((3 + 11 * this.year) / 30) + 227015 - 1;
}
function hijriToString() {
var months = new Array("Muharram","Safar","Rabiul Awwal","Rabiul Tsani","Jumadil Ula","Jumadil Tsani","Rajab","Sya\'ban","Ramadhan","Syawwal","Dzul Qa\'dah","Dzul Hijjah");
return this.day + " " + months[this.month -1]+ " " + this.year;
}
function fixedToHijri(f) {
var i=new Hijri(1100, 1, 1);
i.year = Math.floor((30 * (f - 227015) + 10646) / 10631);
var i2=new Hijri(i.year, 1, 1);
var m = Math.ceil((f - 29 - i2.toFixed()) / 29.5) + 1;
i.month = Math.min(m, 12);
i2.year = i.year;
i2.month = i.month;
i2.day = 1;
i.day = f - i2.toFixed() + 1;
return i;
}
var tod=new Date();
var weekday=new Array("Ahad","Senin","Selasa","Rabu","Kamis","Jumat","Sabtu");
var monthname=new Array("Januari","Februari","Maret","April","Mei"," Juni","Juli","Agustus","September","Oktober","November","Desember");
var y = tod.getFullYear();
var m = tod.getMonth();
var d = tod.getDate();
var dow = tod.getDay();
document.write(weekday[dow] + ", " + d + " " + monthname[m] + " " + y);
m++;
fixd=gregToFixed(y, m, d);
var h=new Hijri(1421, 11, 28);
h = fixedToHijri(fixd);
document.write(" M / " + h.toString() + " H ");
Finally, i can edit it by myself guys, hahaha, even I'm not programmer.
Thank you for your answer. If anyone wan to use this code, here, i'll share it.
function isGregLeapYear(year)
{
return year%4 == 0 && year%100 != 0 || year%400 == 0;
}
function gregToFixed(year, month, day)
{
var a = Math.floor((year -1) / 4);
var b = Math.floor((year - 1) / 100);
var c = Math.floor((year - 1) / 400);
var d = Math.floor((367 * month - 362) / 12);
if (month <= 2)
e = 0;
else if (month > 2&& isGregLeapYear(year))
e = -1;
else e = -2;
return 1 - 1 + 365 * (year - 1) + a - b + c + d + e + day;
}
function Hijri(year, month, day)
{
this.year = year;
this.month = month;
this.day = day;
this.toFixed = hijriToFixed;
this.toString = hijriToString;
}
function hijriToFixed()
{
return this.day +Math.ceil(29.5 * (this.month - 1)) +(this.year - 1) * 354 +
Math.floor((3 + 11* this.year) / 30) + 227015 - 1;
}
function hijriToString()
{
var months = new Array("Muharram","Safar","Rabiul Awal","Rabiul Akhir","Jumadil Awal","Jumadil Akhir","Rajab","Sya'ban","Ramadhan","Syawal","Zulqai'dah","Zulhijjah");
return this.day + " " +months[this.month -1]+ " " + this.year;
}
function fixedToHijri(f)
{
var i=new Hijri(1100, 1, 1);
i.year = Math.floor((30 * (f - 227015) + 10646) / 10631);
var i2=new Hijri(i.year, 1, 1);
var m = Math.ceil((f - 29- i2.toFixed()) / 29.5) + 1;
i.month = Math.min(m, 12);
i2.year = i.year;
i2.month = i.month;
i2.day = 1; i.day = f - i2.toFixed() + 1;
return i;
}
var tod=new Date();
var weekday=new Array ("Ahad","Senin","Selasa","Rabu","Kamis","Jumat","Sabtu");
var monthname=new Array("Januari","Februari","Maret","April","Mei"," Juni","Juli","Agustus","September","Oktober","November","Desember");
var y = tod.getFullYear();
var m = tod.getMonth();
var d = tod.getDate();
var dow = tod.getDay();
document.write(weekday[dow] + ", ");
m++;
fixd=gregToFixed(y, m, d);
var steve=new Hijri(1421, 11, 28);
steve = fixedToHijri(fixd);
document.write(" " + steve.toString() + " ");
document.write("/" + " " + d + " " + monthname[m] + " " + y);
m++;
As easy as it may sound to a seasoned coder. I am a newbie trying to implement this on my clock page. It can contain errors. The idea is to generate a zero in front of single digits (like "02" instead of "2") for display purposes. It works fine with double digits.
This is what I got, but doesn't do the trick. Includes commented lines of different tries I have done. I would appreciate any input guys.
<script>
$(function() {
getdata();
myinterval = setInterval(getdata, 30000);
});
function getdata(){
var dt = new Date();
console.log(dt.getMinutes());
var myhr = dt.getHours();
var mymin = dt.getMinutes();
//if(myhr < 10) myhrstr = '0' + myhr.toString(); else myhrstr = myhr.toString();
//if(myhr.toString().length < 2) myhrstr = '0' + myhr.toString(); else myhrstr = myhr.toString();
//if(myhr.toString().length < 2) myhr = "0"+myhr;
if(myhr.toString().length == 1) myhrstr = "0" + myhr.toString(); else myhrstr = myhr.toString();
//if(mymin < 10) myminstr = '0' + mymin.toString(); else myminstr = mymin.toString();
//if(mymin.toString().length < 2) myminstr = '0' + mymin.toString(); else myminstr = mymin.toString();
//if(mymin.toString().length < 2) mymin = "0"+mymin;
if(mymin.toString().length == 1) myminstr = "0" + mymin.toString(); else myminstr = mymin.toString();
var mystr = myhrstr + myminstr;
$.ajax(
{
url:"clock.php?action=getdata&dt="+mystr,
success:function(result){
$('#content').html(result);
}
}
);
}
</script>
What makes you think your code isn't working? It works fine.
Here's a demo:
function FakeDate() {
this.getHours = function() {
return Math.round(Math.random() * 23);
}
this.getMinutes = function() {
return Math.round(Math.random() * 59);
}
}
var dt = new FakeDate(); // use fakeDate for random time generations
var myhr = dt.getHours();
var mymin = dt.getMinutes();
if (myhr.toString().length == 1) myhrstr = "0" + myhr.toString();
else myhrstr = myhr.toString();
if (mymin.toString().length == 1) myminstr = "0" + mymin.toString();
else myminstr = mymin.toString();
var mystr = myhrstr + myminstr;
console.log(mystr);
One way you can simplify this code is, since you are not using the numeric values, you can call toString right away on the getHours and getMinutes methods. For the same reason there's also no need for extra variables to hold the string values, you can just use the same variable when appending the "0".
// get the strings representing hours and minutes
var myhr = dt.getHours().toString();
var mymin = dt.getMinutes().toString();
// prepend them with zeros if needed
if (myhr.length == 1) myhr = "0" + myhr;
if (mymin.length == 1) mymin = "0" + mymin;
// concatenate them to a 4 digit value
var mystr = myhr + mymin;
Here's a demo:
function FakeDate() {
this.getHours = function() {
return Math.round(Math.random() * 23);
}
this.getMinutes = function() {
return Math.round(Math.random() * 59);
}
}
var dt = new FakeDate(); // use fakeDate for random time generations
// get the strings representing hours and minutes
var myhr = dt.getHours().toString();
var mymin = dt.getMinutes().toString();
// prepend them with zeros if needed
if (myhr.length == 1) myhr = "0" + myhr;
if (mymin.length == 1) mymin = "0" + mymin;
// concatenate them to a 4 digit value
var mystr = myhr + mymin;
console.log(mystr);
simple trick to pad single digit with zero
('0' + 1).slice(-2) // 01
('0' + 23).slice(-2) // 23
var mystr;
if(myhr < 10 ) {
mystr = "0" + myhr.toString();
} else {
mystr = myhr.toString();
}
if (mymin < 10) {
mystr += ":0" + mymin.toString();
} else {
mystr += ":" + mymin.toString();
}
I need to transform 3 form inputs (HH, MM, SS) in seconds with javascript.
I have this code but it has only with 1 form input in seconds : https://jsfiddle.net/94150148/hhomeLc3/
To do this I need a new javascript function.
window.onload = function () {generate()};
function generate() {
var width = 'width=\"' + document.getElementById('width').value + '\" ';
var height = 'height=\"' + document.getElementById('height').value + '\" ';
var ytid = "videoID";
var start = document.getElementById('start').value;
var end = document.getElementById('end').value;
if (start !== "") {
if(ytid === document.getElementById('ytid')) {
ytid += '?start=' + start;
}
else {
ytid += '&start=' + start;
}
}
if (end !== "") {
if (ytid === document.getElementById('ytid')) {
ytid += '?end=' + end;
}
else {
ytid += '&end=' + end;
}
}
document.getElementById('embedcode').value = '<iframe ' + width + height +
'src=\"https://www.youtube.com\/embed\/' + ytid +
'\" frameborder=\"0\"><\/iframe>';
}
function clearall() {
document.getElementById('width').value = 550;
document.getElementById('height').value = 315;
document.getElementById('start').value = "";
document.getElementById('end').value = "";
}
The jsFiddle to play with what I need : https://jsfiddle.net/94150148/ybmkcyyu/
https://jsfiddle.net/ybmkcyyu/3/
EDIT:
Do not display start and end when value is 0
https://jsfiddle.net/ybmkcyyu/6/
EDIT2:
https://jsfiddle.net/ybmkcyyu/7/
if (start !== "") {
ytid += '?start=' + start;
}
if (end !== "") {
if (start == "") {
ytid += '?end=' + end;
}
else {
ytid += '&end=' + end;
}
}
You just need to get value of every fields, as int, then add it with the formula: ((hours * 60) + minutes ) * 60 + secondes
And you might ensure that the result is a number. (if user enter a char instead of a number, it should not display something wrong)
var starth = parseInt(document.getElementById('starth').value);
var startm = parseInt(document.getElementById('startm').value);
var starts = parseInt(document.getElementById('starts').value);
var endh = parseInt(document.getElementById('endh').value);
var endm = parseInt(document.getElementById('endm').value);
var ends = parseInt(document.getElementById('ends').value);
var start = (((starth * 60) + startm) * 60) + starts;
if(isNaN(start) || start === 0)
start = "";
var end = (((endh * 60) + endm) * 60) + ends;
if(isNaN(end) || end === 0)
end = "";
/* (...) */
JS is generally quite good at math.
sHour = document.getElementById('starth').value,
sMin = document.getElementById('startm').value,
sSec = document.getElementById('starts').value,
sTime = (sHour * 3600) + (sMin * 60) + sSec;
https://jsfiddle.net/link2twenty/ybmkcyyu/4/
So I followed a pretty strait-forward video tutorial on adding a clock in your webpage through JS. I have the exact same code, but it's not working on mine. Any suggestions? Thank you!
This is my code:
<body>
<div id="clockDisplay">00:00</div>
<!-- JAVASCRIPT starts here -------------------------------------------------------->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
<script type="text/javascript" language="JavaScript">
$(window).load(function renderTime() {
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" ;
}
if (h < 10) {
h = "0" + h;
}
if (m < 10) {
m = "0" + m;
}
if (s < 10) {
s = "0" + s;
}
var myClock = document.getElementyID('clockDisplay');
myClock.textContent = h + ":" + m + ":" + s + " " + diem;
setTimeout(renderTime()' ,1000) ;
};
renderTime() ;
</script>
<!-- JAVASCRIPT ends here --------------------------------------------------------->
</body>
You have a syntax error (quote mismatch) in your setTimeout code. You should never use a string as the first parameter of setTimeout.
setTimeout(renderTime, 1000);
And you don't need the $(window).load() if you put your Javascript code after the element with id="clockDisplay"
function renderTime() {
...
}
renderTime();
These need to be changed as well.
getElementById()
getMinutes()
Don't know what tutorial your following but I would change this line:
myClock.textContent = h + ":" + m + ":" + s + " " + diem;
to this:
myClock.innerHTML = h + ":" + m + ":" + s + " " + diem;
Too many things to fix here, this is my code :
<body>
<div id="clockDisplay">00:00</div>
<!-- JAVASCRIPT starts here -------------------------------------------------------->
<script type="text/javascript" language="JavaScript">
function renderTime() {
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" ;
}
if (h < 10) {
h = "0" + h;
}
if (m < 10) {
m = "0" + m;
}
if (s < 10) {
s = "0" + s;
}
var myClock = document.getElementById('clockDisplay');
myClock.textContent = h + ":" + m + ":" + s + " " + diem;
}
window.onload = renderTime;
setInterval(renderTime ,1000) ;
</script>
<!-- JAVASCRIPT ends here --------------------------------------------------------->
</body>
To see details fix, go there : Fixed issues detail link
I have created a digital clock on my personal developing website but its not animated...
My javascript is below:
07:23:45 PM
<script>
function webClock() {
var pos = "PM";
var pickTime = new Date();
var h = pickTime.getHours();
var m = pickTime.getMinutes();
var s = pickTime.getSeconds();
if(h == 0){
h = 12;
}else if(h>12){
h = h-12;
pos="AM";
}
if(h<10){
h = "0" + h;
}
if(m<10){
m = "0" + m;
}
if(s<10){
s = "0" + s;
}
document.getElementById('MyClock').innerHTML= h + ":" + m + ":" + s + " " +"pos";
setTimeout(webClock, 500);
}
webClock();
}
</script>