How to display system time? - javascript

I want to display the system time on my jsp page. How can i do it? I'm trying this but only date is getting displayed that and not the time. It's all working fine in Internet Explorer but not in other browsers.
<td colspan="1" height="4" align="left" width="260" >
<font class="welcome1">
<strong>
<script language="JavaScript" src="js/date.js"></script>
<span id="clock">
<script language="JavaScript"
src="js/digitalClock.js"></script>
</span>
</strong>
</font>
</td>

Displaying the time on a web-page using js should be trivial .
new Date().toLocaleString() // displays date and time
new Date().toLocaleDateString() // displays date
new Date().toLocaleTimeString() // displays time

To display time you can use Date.
<html>
<head>
<script type="text/javascript">
<!--
function updateTime() {
var currentTime = new Date();
var hours = currentTime.getHours();
var minutes = currentTime.getMinutes();
var seconds = currentTime.getSeconds();
if (minutes < 10){
minutes = "0" + minutes;
}
if (seconds < 10){
seconds = "0" + seconds;
}
var v = hours + ":" + minutes + ":" + seconds + " ";
if(hours > 11){
v+="PM";
} else {
v+="AM"
}
setTimeout("updateTime()",1000);
document.getElementById('time').innerHTML=v;
}
updateTime();
//-->
</script>
</head>
<body>
<h4>Current Time: <span id="time" /></h4>
</body>
</html>
I've tested it in firefox and chrome. Found on this site.
Edit: time now gets updated every second.

You should read the documentation about the Date object in JavaScript (Date). It would be easier if you post the JS source.

/* set Date */
function tick() {
/* Get date in epoch */
var epoch = Date.now();
document.querySelector("#epoch").innerHTML = epoch;
/* Separate epoch */
var datetime = new Date(epoch);
var year = datetime.getFullYear();
var month = datetime.getMonth() + 1; // (0-11)
var date = datetime.getDate();
var hour = datetime.getHours();
var minute = datetime.getMinutes();
var second = datetime.getSeconds();
document.querySelector("#datetime").innerHTML =
year + "-" + addZero(month) + "-" + addZero(date) + " " +
addZero(hour) + ":" + addZero(minute) + ":" + addZero(second);
}
// Add 0 if argument < 10
function addZero(i) {
if (i < 10) {
i = "0" + i
};
return i;
}
/* Call tick in interval 1 second */
setInterval(tick, 1000);
<p id="epoch"></p>
<p id="datetime"></p>

This seems the easiest solution, which uses setInterval with two arguments, the first being a callback, the second the interval in ms:
setInterval(function(){
document.write(new Date().toLocaleTimeString();
},1000);
So my solution should be the accepted answer because it is a real time.

For Date You can use below Javascript. Time will display in a text box. You can modify as per your requirement.
<html>
<head>
<script type="text/javascript">
var timer = null
function stop()
{
clearTimeout(timer)
}
function start()
{
var time = new Date()
var hours = time.getHours()
var minutes = time.getMinutes()
var seconds = time.getSeconds()
var clock = hours + ":" + minutes + ":" + seconds
document.forms[0].display.value = clock
timer = setTimeout("start()",1000)
}
</script>
</head>
<body onload="start()" onunload="stop()">
<form>
<input type="text" name="display" size="20">
</form>
</body>
</html>

Related

This code returns unexpected identifier in the chrome console.But still this function works and returns the answer.Were have i gone wrong?

I have tried to calculate the duration of the shift.It works well for foth day and night shift timings.But y does this returns error.In the console it returns unexpected identifier error but the code works and returns the answer.I think There might be an issue in the if part.But as far as i have seen,I couldnt find anything
$("#formShiftEndTime").on("change", function() {
var startHour = $("#formShiftStartTime").val();
var endHour = $("#formShiftEndTime").val();
calculate_time(startHour, endHour);
// console.log(startHour);
})
function showTime(hours, minutes) {
return ((hours < 10) ? '0' : '') + hours +
':' +
((minutes < 10) ? '0' : '') + minutes;
}
var startHour = $("#formShiftStartTime").val();
var endHour = $("#formShiftEndTime").val();
function calculate_time(formShiftStartTime, formShiftEndTime) {
if (($("#formShiftStartTime").val()) < ($("#formShiftEndTime").val()))
{
startTime = new Date('1-1-1 ' + formShiftStartTime);
endTime = new Date('1-1-1 ' + formShiftEndTime);
} else {
startTime = new Date('1-1-1 ' + formShiftStartTime);
endTime = new Date('1-2-1 ' + formShiftEndTime);
}
var difference = endTime - startTime;
difference /= 1000 * 60; // convert to minutes
var hours = Math.floor(difference / 60);
var mins = Math.floor(difference % 60);
document.getElementById('formDuration').value = showTime(hours, mins);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<form id="calculate" action="">
<div>
<p><label>Start Hour: <input type="time" name="formShiftStartTime" id="formShiftStartTime"/></label></p>
<p><label>End Hour: <input type="time" name="formShiftEndTime" id="formShiftEndTime" /></label></p>
<div class="form-group">
<label class="col-md-4 control-label">Duration</label>
<div class="col-md-8">
<input type="text" class="form-control " id="formDuration" name="formDuration">
</div>
</div>

JavaScript clock not displaying properly

I'm trying to make an updating JavaScript clock on my webpage. The problem I'm having is that, while the value itself updates (I use alert(timeNow) to show the value and make sure it's updating), the clock on the website doesn't. I was just wondering if there was something I was missing, or if I've just happened to come across something that I can't quite do. I'd prefer if there was a way to do it using jQuery, as I understand that a little better than normal JavaScript.
Javascript:
function updateClock() {
var thisDate = new Date();
if (thisDate.getHours() > 11 && thisDate.getHours() != 0) {
var Hours = Math.abs(thisDate.getHours() - 12);
var AmPm = "PM"
} else {
var Hours = thisDate.getHours()
var AmPm = "AM"
}
if (thisDate.getMinutes() < 10) {
var Mins = "0" + thisDate.getMinutes();
} else {
var Mins = thisDate.getMinutes();
};
var timeNow = thisDate.getDate() + "/" + (thisDate.getMonth() + 1) + "/" + thisDate.getFullYear() + " " + Hours + ":" + Mins + " " + AmPm;
return timeNow;
};
setInterval(updateClock, 1000);
$("span#time").append(updateClock());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span id="time"></span>
You are not consuming the return value of updateClock function, thus the updated time is not reflecting.
You should update the text of time span
Use
setInterval(function(){
$("span#time").text(updateClock());
}, 1000);
You are returning the time in the function updateClock(). What you actually want to do is to set it into the DOM at the end of updateClock(). Here is an updated example:
function updateClock() {
var thisDate = new Date();
if (thisDate.getHours() > 11 && thisDate.getHours() != 0) {
var Hours = Math.abs(thisDate.getHours() - 12);
var AmPm = "PM"
} else {
var Hours = thisDate.getHours()
var AmPm = "AM"
}
if (thisDate.getMinutes() < 10) {
var Mins = "0" + thisDate.getMinutes();
} else {
var Mins = thisDate.getMinutes();
};
var timeNow = thisDate.getDate() + "/" + (thisDate.getMonth()+1) + "/" + thisDate.getFullYear() + " " + Hours + ":" + Mins + " " + AmPm;
$("span#time").text(timeNow);
}
setInterval(updateClock, 1000);
You could of course also just use the returned value of updateClock() to update the DOM. In this way, you would separate the DOM manipulation and the JavaScript time calculation. #Satpal described this way.
Try This...
$(document).ready(function()
{
goforit();
});
var dayarray=new Array ("Sunday","Monday","Tuesday","Wednesday",
"Thursday","Friday","Saturday")
var montharray=new Array("January","February","March","April","May","June",
"July","August","September","October","November","December")
function getthedate() {
d = new Date();
d.setUTCFullYear(2004);
d.setUTCMonth(1);
d.setUTCDate(29);
d.setUTCHours(2);
d.setUTCMinutes(45);
d.setUTCSeconds(26);
var mydate=new Date()
var year=mydate.getYear()
if (year < 1000)
year+=1900
var day=mydate.getDay()
var month=mydate.getMonth()
var daym=mydate.getDate()
if (daym<10)
daym="0"+daym
var hours=mydate.getHours()
var minutes=mydate.getMinutes()
var seconds=mydate.getSeconds()
var dn=""
if (hours>=12)
dn=""
if (hours>12){
hours=hours-12
}
if (hours==0)
hours=12
if (minutes<=9)
minutes="0"+minutes
if (seconds<=9)
seconds="0"+seconds
//Hire change font size
var cdate=""
+ mydate.toLocaleString()
+""
if (document.all)
document.all.clock.innerHTML=cdate
else if (document.getElementById)
document.getElementById("clock").innerHTML=cdate
else
document.write(cdate)
}
if (!document.all&&!document.getElementById)
getthedate()
function goforit()
{
if (document.all||document.getElementById)
setInterval("getthedate()",1000)
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<SPAN id=clock style="display:block"></SPAN>
setInterval(function() {
$("span#time").text(moment(new Date()).format('DD/M/YYYY LTS'));
}, 1000);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://momentjs.com/downloads/moment.js"></script>
<span id="time"></span>

Subtract to function times

I currently have two functions that capture the current dates minute in which a user loads and leaves a page.
Is there a way to combine these functions so that I can get the difference?
Ex. User loads the page at 30, and leaves at 45
Therefore, 45-30 = 15 minutes
Also is there any reason why my unload alert does not work on safari?
JAVASCRIPT
<script type="text/javascript">
window.onload = function () {
var currentdate = new Date();
var hour = currentdate.getHours();
var minutes = currentdate.getMinutes();
var seconds = currentdate.getSeconds();
alert("starts at " + minutes + " minutes");
}
window.onbeforeunload = function (e) {
var currentdate = new Date();
var hour = currentdate.getHours();
var minutes = currentdate.getMinutes();
var seconds = currentdate.getSeconds();
return ("leaves at " + minutes + " minutes");
}
</script>
Something like this ?
var pageLoadTime;
window.addEventListener("load", function () {
pageLoadTime = (new Date()).getTime();
});
window.addEventListener("beforeunload", function (e) {
var pageUnloadTime = (new Date()).getTime();
var secondsPassed = Math.round((pageUnloadTime - pageLoadTime) / 1000);
var hoursPassed = Math.floor(secondsPassed / 3600);
secondsPassed = secondsPassed % 3600;
var minutesPassed = Math.floor(secondsPassed / 60);
secondsPassed = secondsPassed % 60;
alert(hoursPassed + " hour(s), " + minutesPassed + " minute(s), " + secondsPassed + " second(s)");
});

onload doesn't work while onmouseenter does

I have done a simple JS function and tried to call it with onload="updateClock()" but without any success. But if i change to onmouseenter="updateClock()" it works perfectly then I hover over with the mouse.
Why doesn't it work?
HTML:
<script src="clock.js" type="text/javascript"></script>
<section onload="updateClock();">
<span id="clock">00:00:00</span>
</section>
JS:
function updateClock(){
var currentTime = new Date ();
var hours = currentTime.getHours ();
var minuts = currentTime.getMinutes ();
var seconds = currentTime.getSeconds ();
//Pad with zeros
hours = (hours < 10 ? "0" : "") + hours;
minuts = (minuts < 10 ? "0" : "") + minuts;
seconds = (seconds <10 ? "0" : "") + seconds;
var time = hours + ":" + minuts + ":" + seconds;
document.getElementById("clock").innerHTML = time;
}
Only elements like iframe or img, in general, elements which can have content loaded from an external resource, have onload event. (And some DOM objects, like window ofcourse.)
A quick-fix would be to move the script tag after the section and use an IIFE:
<section>
<span id="clock">00:00:00</span>
</section>
<script src="clock.js" type="text/javascript"></script>
And in clock.js:
(function updateClock(){
:
}());

when implementing javascript countdown the other html elements disappear

I made a layout and had everything set and when I implement the counter portion under my text all the other HTML elements disappear why is that? Also is there any way I can make an email alert when the counter gets to a specific time?
<!doctype html>
<html lang="en">
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
<meta charset="utf-8" />
<meta name="viewport" content="initial-scale=1.0, maximum-scale=1.0, user-
scalable=0, width=device-width;">
<title>Welcome to Tiffany & Co.</title>
<link rel="stylesheet" href="index.css"
type="text/css" media="screen" />
<script src="http://code.jquery.com/jquery-1.7.2.min.js"></script>
<!--Enable media queries in some unsupported subrowsers-->
<script type="text/javascript" src="css3-mediaqueries.js"></script>
<script type="text/javascript" src="main.js"></script>
</head>
<body>
<div id="wrapper">
<h1>Welcome to Store</h1>
<p>The WiFi Password is:</p>
<h2 align=center>
<font color="red">Diamonds</font>
</h2>
<p>It will change in:</p>
<p>
<script type="text/JavaScript">
window.document.onload = function () {
tick();
setInterval(tick, 1000);
};
function tick() {
var d = new Date();
var currentDate = new Date(d.getUTCFullYear(),
d.getUTCMonth(), d.getUTCDate(), d.getUTCHours(),
d.getUTCMinutes(), d.getUTCSeconds(),
d.getUTCMilliseconds());
var endDate = new Date(currentDate.getFullYear(),
currentDate.getMonth(), currentDate.getDate() + (30
/*
saturday */
- currentDate.getDay()), 16
/* 9 AM Mountain
Time = 4 PM GMT */
);
var secondsUntilSaturday = Math.floor((endDate.getTime() - currentDate.getTime()) / 1000);
var timeUntilSaturday = secondsToTime(secondsUntilSaturday);
document.body.innerHTML = (timeUntilSaturday.h + " hours, " + timeUntilSaturday.m + " minutes, " + timeUntilSaturday.s + "
seconds");
}
function secondsToTime(secs) {
var hours = Math.floor(secs / (60 * 60));
var divisor_for_minutes = secs % (60 * 60);
var minutes = Math.floor(divisor_for_minutes / 60);
var divisor_for_seconds = divisor_for_minutes % 60;
var seconds = Math.ceil(divisor_for_seconds);
var obj = {
"h": hours,
"m": minutes,
"s": seconds
};
return obj;
}
</script>
<div id="logo">
<img src="logo.png" width="108" height="14" alt="Tiffany & Co." />
</div>
</div>
</body>
</html>
Your HTML content disappears because of the line:
document.body.innerHTML = (timeUntilSaturday.h + " hours, " + timeUntilSaturday.m + " minutes, " + timeUntilSaturday.s + " seconds");
document.body.innerHTML will write content to the body element, replacing anything that's there. You can replace document.body.innerHTML with document.write.
To answer your second question, no JavaScript can't send email on it's own, but via AJAX it can call a script on your server to send email.
That's because you're replacing whole body content with your timer
document.body.innerHTML = (
timeUntilSaturday.h +" hours, "+
timeUntilSaturday.m +" minutes, "+ timeUntilSaturday.s +"
seconds"
);
Instead of this add <div> for timer and set content with your timer
<div id="timer"></div>
<script>
document.getElementById('timer').innerHTML = (
timeUntilSaturday.h +" hours, "+
timeUntilSaturday.m +" minutes, "+ timeUntilSaturday.s +"
seconds"
);
</script>
Since you're refrencing JQuery, I've used that for you, but really only in one spot...
This should do what you need it to do: Here's a fiddle
Also here's the code from that fiddle:
<script>
//start your interval to update your timer.
setInterval(function() {
//get ms until Saturday 9AM.
var ms = untilTimeOfWeek(6, 9, 0, 0);
$('#timer').text(getHours(ms) + ' hours ' + getMinutes(ms) + ' minutes ' + getSeconds(ms) + ' seconds');
}, 100);
//gets the time left until a specific time of week.
function untilTimeOfWeek(day, hour, min, sec) {
var currdate = new Date();
var currday = currdate.getDay();
var daydiff = (day - currdate.getDay()) * 86400000;
var hourdiff = (hour - currdate.getHours()) * 3600000;
var mindiff = (min - currdate.getMinutes()) * 60000;
var secdiff = (sec - currdate.getSeconds()) * 1000;
return daydiff + hourdiff + mindiff + secdiff;
}
//get the hours from some milliseconds.
function getHours(ms) {
return Math.floor(ms / 3600000);
}
//get the minutes from some milliseconds.
function getMinutes(ms) {
return Math.floor((ms % 3600000) / 60000);
}
//get the seconds from some milliseconds.
function getSeconds(ms) {
return Math.floor(((ms % 3600000) % 60000) / 1000);
};​
</script>
<div id="timer"></div>
NOTE: +new Date is just shorthand for converting a Date to a numeric type in JavaScript.
I hope that helps.
EDIT: Updated to get 9am the following Saturday.

Categories

Resources