I am trying to show a live javascript clock on my page which shows the time on the server. I found this snippet of code on the internet a few weeks back however it doesn't seem to be doing what it claimed to do. It is showing the client time, not the server time. Any idea why?
flag = true;
timer = '';
setInterval(function(){phpJavascriptClock(<?php echo time(); ?>);},1000);
function phpJavascriptClock(timestamp)
{
if ( flag ) {
timer = timestamp * 1000;
}
var d = new Date(timer);
var currentDate = d.getDate();
currentDate = currentDate < 10 ? '0'+currentDate : currentDate;
var hours = d.getHours();
var minutes = d.getMinutes();
var seconds = d.getSeconds();
var ampm = hours >= 12 ? 'PM' : 'AM';
hours = hours % 12;
hours = hours ? hours : 12; // the hour ’0' should be ’12'
minutes = minutes < 10 ? '0'+minutes : minutes;
seconds = seconds < 10 ? '0'+seconds : seconds;
var strTime = hours + ':' + minutes + ' ' + ampm;
var output = '';
output +=
'<a>'
+ '<i class="ace-icon fa fa-clock-o"></i>'
+ '<span class="">' + strTime + ' (SA)</span>'
+ '</a>'
;
document.getElementById("current_time").innerHTML = output ;
flag = false;
timer = timer + 1000;
}
I see these 4 constructors for a Javascript DATE:
new Date()
new Date(milliseconds)
new Date(dateString)
new Date(year, month, day, hours, minutes, seconds, milliseconds)
Could it be your timestamp is not milliseconds or dateString so Javascript just creates a new Date() object without any parameters (which is then the client time)?
Wrote a new jQuery based clock. Although it polls the server every minute, it works.
My controller that passes the time:
public function getServerTimeAction() {
global $config;
try{
$return["time"] = date("H:i a");
$return["timezone"] = $config->application->timezone;
$this->returnJson( JsonReturnObject::success( $return ) ) ;
} catch ( Exception $e ) {
$this->returnJson( JsonReturnObject::error( $e ) );
}
}
The jquery code:
function getServerTime() {
$.ajax({
url : "{{ url('json/session/get-server-time') }}",
cache : false,
success : function ( data ) {
if ( data.success ) {
var output = '';
output +=
'<a>'
+ '<i class="ace-icon fa fa-clock-o"></i>'
+ '<span class="">' + data.data.time + ' (SA)</span>'
+ '</a>'
;
$("#current_time").html(output);
setTimeout(getServerTime, 60000);
}
}
})
}
Related
var dateObj = new Date();
var month = dateObj.getUTCMonth() +1;
var day = dateObj.getUTCDate();
var year = dateObj.getUTCFullYear();
var nowhour = dateObj.getHours();
var nowday = dateObj.getUTCDate();
var hour = "03";
var min = "00";
var hour2 = "18";
var min2 = "00";
var hour3 = "21";
var min3 = "00";
if(hour == 03)
{
day++;
}
document.write(nowhour);
newdate = year + "/" + month + "/" + day;
hourdate = " " + hour + ":" + min;
hourdate2 = " " + hour2 + ":" + min3;
hourdate3 = " " + hour2 + ":" + min3;
$("#bifrost")
if(nowhour > hour && day > nowday)
{
.countdown(newdate + hourdate, function (event) {$(this).text(event.strftime('%H:%M:%S'));});
}else if(nowhour > hour2)
{
.countdown(newdate + hourdate2, function (event) {$(this).text(event.strftime('%H:%M:%S'));});
}else{
.countdown(newdate + hourdate3, function (event) {$(this).text(event.strftime('%H:%M:%S'));});
}
Hello, i wanna make a countdown timer for events. I have 3 different event time,i wanna show up coming event here is my javascript code.
can anyone help me ?
ps: sorry for my bad english.
If countdown is a global function, you do not need the period before the call, just
countdown(parameters ... );
If countdown is a jquery plugin you have, and you are trying to call it on the jQuery object you created before the if statements, you must do it like this
$("#bifrost").countdown(parameters ... );
And repeat the jQuery selector in each of your if statements.
There is built in function setTimeout(function,milliseconds,param1,param2,...). Please see for examples in here.
setTimeout(function_to_do, miliseconds to wait) - will be triggered once;
setInterval(function_to_do, miliseconds to wait) - will be triggered periodically.
By the way - function name can't start with dot - and you have three calls to something .countdown(... There is you error.
I am trying to have a div show the current time but it always shows it in military time, so I went to use an if / else statement to help but it doesn't seem to work.
Javascript
var time = new Date(Date.now());
var timeHour = time.getHours();
var timeHourFix = timeHour;
var timeMinute = time.getMinutes();
var formatted = timeHourFix + ":" + timeMinute;
if(time.getHours() > 12) {
timeHourFix = time.getHours() - 12 + "PM";
}else {
timeHourFix = time.getHours() + "AM";
};
$( document ).ready(function() {
$('#hourmin').text(formatted)
});
it should display the time like 5:35 PM but it still shows 17:35
That's because your are declaring the variable formatted before the timeHourFix is actually modified. Try the code below.
var time = new Date(Date.now());
var hour = time.getHours();
var t_hour = hour > 12 ? (hour - 12) : ((hour == 0) ? hour + 12 : hour);
var formatted = t_hour + " : " + time.getMinutes() + (hour > 11 ? " PM" : " AM");
$( document ).ready(function() {
$('#hourmin').text(formatted)
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p id=hourmin>
The time is not being formatted because the variable formatted is being set before timeHourFix or timeHour is being set. I think it's easiest to set formatted in the if else statement directly:
var time = new Date(Date.now());
var timeHour = time.getHours();
var timeMinute = time.getMinutes();
var formatted;
if(time.getHours() > 12) {
formatted = time.getHours() - 12 + ":" + timeMinute + " PM";
} else {
formatted = time.getHours() + ":" + timeMinute + " AM";
};
$( document ).ready(function() {
$('#hourmin').text(formatted)
});
In your case the problem was you were modifying the variable timeHourFix after it was appended to the string, there is no live linking between the string and the timeHourFix variable so any changes you make to the variable after the string concatenation will not be reflected in the original value.
Also there are multiple other issues like the AM/PM should be at the end of the string so that also have to be changed. Also there are other issues with timeHourFix like how the value 0030 will be handled, it should be shown as 12:30 AM not 00:30 AM
var time = new Date(Date.now());
var timeHour = time.getHours();
//set the hour part
var timeHourFix = timeHour > 12 ? timeHour - 12 : timeHour == 0 ? 12 : timeHour;
var timeMinute = time.getMinutes();
var formatted = timeHourFix + ":" + timeMinute;
//set the AM/PM at the end of the string
formatted += timeHour >= 12 ? ' PM' : ' AM';
$(document).ready(function() {
$('#hourmin').text(formatted)
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="hourmin"></div>
Because you set formatted before setting the right values to timeHourFix. Move the assignment of formatted to below the else block.
You could always do something like this if you want to simplify your code.
var time = new Date(Date.now());
var timeHour = time.getHours();
var timeHourFix = timeHour;
var timeMinute = time.getMinutes();
$(document).ready(function() {
var timeofday = "";
if(timeHour > 12) {
timeHourFix = timeHour - 12;
timeofday = "PM";
}else {
timeHourFix = timeHour;
timeofday = "AM";
};
var formatted = timeHourFix + ":" + timeMinute + " " + timeofday;
$('#hourmin').text(formatted)
});
This is perfectly working full code.
var time = new Date(Date.now());
var timeHour = time.getHours();
var timeHourFix = timeHour;
var timeMinute = time.getMinutes();
var formatted = timeHourFix + ":" + timeMinute;
if(time.getHours() > 12) {
time = time.getHours() - 12 + " : " + timeMinute + " PM";
}
else {
time = time.getHours() +" : " + timeMinute + " AM";
};
$( document ).ready(function() {
$('#hourmin').text(time)
});
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
</head>
<body>
<p id="hourmin">Time Display</p>
</body>
</html>
i'm trying to use the gethours() method in javascript but it keeps returning military time. can someone please help me out fixing it so that it displays clock time? (1-12). Thank you so much!
// Reroute from the conf.js script
var chat = $( '.chat-output' ),
message = function ( message, userId ) {
var dt = new Date(),
time = dt.getHours() + ":" + dt.getMinutes(); // + ":" + dt.getSeconds();
return $( '<div class="chat-message color-' + users[userId] + '">' +
'<div class="chat-id color-' + users[userId] + '"></div>' +
'<div class="chat-user-message">' + message + '</div>' +
'<div class="chat-time">' + time + '</div>' +
'</div>' );
},
addText = function ( text ) {
// log.innerHTML += text;
// log.scrollTop = log.scrollHeight;
console.log( text );
},
addRemoteText = function ( userId, text ) {
// addText( '[' + userId + ']: ' + text+'<br>' );
chat.append( message( text, userId ) );
chat.scrollTop( chat.get( 0 ).scrollHeight );
};
function ampm(date){
var dt= date || new Date,
h= dt.getHours(),
m= dt.getMinutes(),
s= dt.getSeconds(),
ampm;
if(h>12){
h-= 12;
ampm= (h%12)? ' PM': ' AM';
}
else ampm= (h%12)? ' AM': ' PM';
m= m<10? '0'+m: m;
s= s<10? '0'+s: s;
return [h, m, s].join(':')+ampm;
}
ampm()
/* returned value: (String)
11:52:55 PM
*/
Something like this?
var dt = new Date();
var hours = dt.getHours();
var ampm = hours > 11 ? 'PM' : 'AM';
if (hours > 12) {
hours -= 12;
} else if (hours === 0) {
hours = 12;
}
var time = hours + ":" + dt.getMinutes() + ' ' + ampm;
Fiddle
Here's another version of formatting a time in 12 hour format:
// Returns formatted time for given Date object, or
// current system time if d is falsey.
function getTime(d) {
d = d || new Date();
var hrs = d.getHours();
var pad = function(n){return (n<10?'0':'')+ +n};
return pad(hrs%12 || 12) + ':' + pad(d.getMinutes()) + ' ' + (hrs<12? 'AM':'PM');
}
console.log(getTime(new Date(2014,2,24, 0, 5))); // 12:05 AM
console.log(getTime(new Date(2014,2,24,10,25))); // 10:25 AM
console.log(getTime(new Date(2014,2,24,20,15))); // 08:15 PM
Note that 24hr time is preferred in many cases to avoid anomalies like 12:00 AM (which is really neither AM or PM) and 12:00 AM being before 01:00 AM.
I have checked out this thread and this one but it didn't really help me.
I have a ASP:CheckBox control shown below.
<asp:CheckBox ID="chbArchived" runat="server" Checked='<%# Bind("archived") %>' OnClick=changeExpirationDate() />
My JavaScript are follows:
<script type="text/javascript">
$(document).ready(function () {
//alert("got here");
$('.insDateTime').datetimepicker({
ampm: true
});
changeExpirationDate(){
var currentDate = new Date;
var futureDateTime = (currentDate.getMonth() + 4) + '/' + currentDate.getDate() + '/' + currentDate.getFullYear() + ' ' + formatAMPM(currentDate);
var expiredDateTime = (currentDate.getMonth() + 1) + '/' + currentDate.getDate() + '/' + currentDate.getFullYear() + ' ' + formatAMPM(currentDate);
var archivedCheckbox = document.getElementById('cphContent_fmvNewsEventList_chbArchived').checked;
if(archivedCheckbox == true)
{
document.getElementById('cphContent_fmvNewsEventList_txtExpirationDate').value = expiredDateTime;
}
else{
document.getElementById('cphContent_fmvNewsEventList_txtExpirationDate').value = futureDateTime;
}
};
function formatAMPM(date) {
var hours = date.getHours();
var minutes = date.getMinutes();
var ampm = hours >= 12 ? 'pm' : 'am';
hours = hours % 12;
hours = hours ? hours : 12; // the hour '0' should be '12'
minutes = minutes < 10 ? '0'+minutes : minutes;
var strTime = hours + ':' + minutes + ' ' + ampm;
return strTime;
};
});
</script>
The problem is I kept getting this JavaScript error "Uncaught ReferenceError: changeExpirationDate is not defined" when I clicked on the checkbox. Any suggestion/help is much appreciated.
});
changeExpirationDate(){ <-- where is the function declaration?
var currentDate = new Date;
aka
function changeExpirationDate () {
Change
changeExpirationDate(){
to
function changeExpirationDate(){
The first makes it look like you are trying to call it; the second defines it.
Okay, after looking at one more time, I found out it was a very stupid mistake. I forgot the "function" before the function name, changeExpirationDate(), thus, it was giving me this error.
I have the following javascript that prints the timestamp:
<script type="text/javascript">
<!--
var currentTime = new Date()
var hours = currentTime.getHours()
var minutes = currentTime.getMinutes()
var seconds = currentTime.getSeconds()
var month = currentTime.getMonth() + 1
var day = currentTime.getDate()
var year = currentTime.getFullYear()
document.write(hours + "" + minutes + seconds + month + "" + day + "" + year)
//-->
</script>
However I want to use this timestamp in many places in the page, how can i call it like $timestamp so i can control where its placed?
Thanks in advance.
Set a variable, like:
var timestamp = hours + "" + minutes + seconds + month + "" + day + "" + year;
and later in code use that variable to show info in your page, like:
var container = document.getElementById('container1');
container.innerHTML = timestamp;
where 'container1' is a html element like span, div, p, etc. ex:
<span id="container1"></span>
answer
<script>
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('txt').innerHTML=h+":"+m+":"+s;
t=setTimeout('startTime()',500);
}
function checkTime(i)
{
if (i<10)
{
i="0" + i;
}
return i;
}
</script>
<span id="txt"></span>
<script type="text/javascript">
startTime().swap('txt');
</script>