Something in my code is not working. I am new to this. I think it is the onload maybe?
I am trying to convert a 24 clock to a 12 hour GMT server time clock and I have got as far as passing my new code to the CSS div I made.
All the CSS is fine and my coding works well with alert but not with onload and document.getElementById.
<script>
var currenttime = '<? print date("F d, Y H:i:s a", time())?>'
var serverdate=new Date(currenttime)
var formatTime = (function () {
function addZero(num) {
return (num >= 0 && num < 10) ? "0" + num : num + "";
}
return function (dt) {
var formatted = '';
if (dt) {
var hours24 = serverdate.getHours();
var hours = ((hours24 + 11) % 12) + 2;
formatted = [formatted, [addZero(hours), addZero(serverdate.getMinutes())].join(":"), hours24 > 11 ? "pm" : "am"].join(" ");
}
document.getElementById("servertime").innerHTML=formatted
return formatted;
}
})();
window.onload=function(){
formatTime(new Date())
}
</script>
</head>
<body>
<h1><p><span id="servertime"></span></p></h1>
</body>
You could just write this, no need for javascript at all.
<h1><p><span id="servertime"><? print date("F d, Y h:i:s a", time())?></span></p></h1>
In case you are preparing a periodic update with your javascript (here it makes sense), I suggest using a simple jquery script for it:
$(document).ready(function() {
function update() {
$.ajax({
type: 'POST',
url: 'servertime.php',
timeout: 1000,
success: function(data) {
$("#servertime").html(data);
window.setTimeout(update, 1000);
},
});
}
update();
});
Related
So I am trying to store the date inside a database and to do so I need to pass the variable 'date' to the PHP file store.pro.php however, I am not sure how to do this. I have tried Ajax but at the moment it doesn't seem to be working.
Javascipt code:
// variables for fetching current date
n = new Date();
y = n.getFullYear();
m = n.getMonth() + 1;
d = n.getDate();
// variables for displaying current date
let displayDay = 0;
let displayMonth = 0;
// If m or d are only one digit, add a leading 0 to the value
if (d < 10) {
displayDay = '0' + d.toString();
} else {
displayDay = d.toString();
}
if (m < 10) {
displayMonth = '0' + m.toString();
} else {
displayMonth = m.toString();
}
// storing the current date within raceDate
var date = displayDay + '/' + displayMonth + '/' + y;
$.ajax({
url: "processes/store.pro.php",
type: "POST",
data: { x: date }
});
PHP code in store.pro.php
if (isset($_POST['x'])) {
$raceDate = $_POST['x'];
echo($raceDate);
} else {
echo "no";
}
How do you know "it doesn't seem to be working" ?
add success method to your ajax, like this:
$.ajax({
url: "processes/store.pro.php",
type: "POST",
data: { x: date },
success: function(res) {
res = JSON.parse(res);
console.log(res);
}
});
Then, in store.pro.php put this:
if (isset($_POST['x'])) {
$raceDate = $_POST['x'];
echo json_encode($raceDate);
} else {
echo json_encode("no");
}
exit; // You may need remove this line, after you check, that ajax call is working
and check console in your browser
I use final countdown to countdown timer. I provide an enddate and it works fine.
<div class="js-countdown" data-enddate="2019/1/21 15:54"></div>
my js:
var $clock = $('.js-countdown');
var d = new Date(Date.parse($clock.data("enddate").replace(/ /g, "T")));
$clock.countdown(d, function(event) {
$(this).text(
event.strftime('%D days %H:%M:%S')
);
});
</script>
It really depends on user clock, for example, when user changes time or if clock is not synced, the countdown timer doesn't work as expected.
Server time: 13:54
User time: 13:54
End date: 15:54, then countdown shows: 2(hrs):00(mins). But if:
Server time: 13:54
User time: 14:54 (it changed deliberately)
End date: 15:54, then countdown shows 1(hrs):00(mins) as I want it be 2(hrs):00(mins). How can I do change this behavior? My goal is to achieve an independent countdown timer. Would you please give me hints about that?
Edit
Here, the timer updates date. Is it reasonable to send request every time that update event fire?
I'm not sure if this is the best approach, but by now, it works fine.
var now;
var it = 1;
now = new Date(Date.parse('#DateTime.UtcNow.ToString("u")'.replace(/ /g, "T")));
setInterval(setAndSyncTime, 1000);
function setAndSyncTime() {
var t1 = new Date();
var t2 = now;
var t3 = Math.abs(t1 - t2);
if (t3 > 2000) {
if (it === 10) {
it = 0;
$.ajax({
url: '/SyncTime',
type: 'get',
success: function (response) {
now = new Date(Date.parse(response.replace(/ /g, "T")));
}
});
} else {
now = now.setSeconds(now.getSeconds() + 1);
now = new Date(now);
}
} else {
now = now.setSeconds(now.getSeconds() + 1);
now = new Date(now);
}
it++;
}
and
public virtual JsonResult SyncTime()
{
return Json(DateTime.UtcNow.ToString("u"), JsonRequestBehavior.AllowGet);
}
I have the following Jquery script that calculates the number of days between two dates and changes the color of the cell according to the time left.
Now, the calculation works but what it doesn't work all the times is that when I open the tab where this information is displayed most of the times the first time I open it, it works but then if I click on it again or if I click on another tab, it won't display the change of color.
<script>
function expiryDates() {
var warning = "<?php echo config('WARNING_DATE')?>";
var critical = "<?php echo config('CRITICAL_DATE')?>";
//gets and creates array of all TD 'lod' dates
var expDate = "<?php echo $content['lod'] ?>";
//var value = $(this).text();
expDate = expDate.split("-");
//Gets today's date and formats it to MYSQL date format
var now = (new Date()).toISOString().substring(0, 10);
now = now.split("-");
//Converts all TD dates into days
var eDate = new Date(expDate[0] + "-" + expDate[1] + "-" + expDate[2]);
//Converts today's date into day
var sDate = new Date(now[0] + "-" + now[1] + "-" + now[2]);
//Does the math
var daysApart = Math.abs(Math.round((sDate - eDate) / 86400000));
//Changes cells color
if (daysApart < critical) {
//$("#expiration-date").addClass('expired');
$("#expiration-date").css("color", "red");
} else if ((daysApart > critical) && (daysApart <= warning)) {
$("#expiration-date").css("color", "#orange");
// $("#expiration-date").addClass('about_expired');
} else if (eDate < sDate) {
$("#expiration-date").css("color", "red");
// $("#expiration-date").addClass('expired');
}
}
</script>
I have used as well:
$( document ).ready( expiryDates);
and
$( window ).on( "load", expiryDates);
but the result is the same.
Any input would be appreciated.
Thank you!
Edit:
Sorry for the missing information.
The way this is setup, is that I have a main blade that calls this information tab:
The main blade has this code:
<td class="detail-slide-specifications" id="detail-slide-specifications{{ $item['mainHwID'] }}" onclick="showSpecifications({{ $item['mainHwID'] }})">
and this is the AJAX call:
function showSpecifications(masterID)
{
var itemID = "#detail-panel-specs" + masterID ;
var loadingImgClass = ".specifications_loading_spinner_" + masterID ;
if (masterID == "") {
$(itemID).html( "Error : No Master ID");
return;
} else {
var request = $.ajax({
url: "get_specifications?masterID=" + masterID,
type: "get",
timeout: 5000
});
request.done(function (responseText) {
$(loadingImgClass).hide();
$(itemID).html(responseText);
});
request.fail(function (jqXHR, textStatus, errorThrown) {
$(loadingImgClass).hide();
$(itemID).html("Error " + errorThrown);
});
}
}
I am working with MediaWiki's UTCLiveClock.js and I am trying to configure it to put out a display time in PST/PDT. I thought I fixed the problem, however when midnight UTC hit (00:00:00) it changed my time output to 0-7:00:00. I need to to display properly so that when UTC 00:00:00 - 07:00:00 occurs, my time display doesn't look a mess. The gadget I am using through mediawiki can be found at https://www.mediawiki.org/wiki/MediaWiki:Gadget-UTCLiveClock.js
Yes, I'm a noob. I don't have any formal programming knowledge. I'm just trying to build a wiki for a game whose server exists in PST/PDT and running into this problem. Googling keyword searches for the last 3 hours has gotten me nowhere. Please help.
*/
/*global mw, $, UTCLiveClockConfig:true */
mw.loader.using(['mediawiki.util', 'mediawiki.api', 'mediawiki.notify']).then( function () {
var $target;
function showTime( $target ) {
var now = new Date();
var hh = now.getUTCHours();
var mm = now.getUTCMinutes();
var ss = now.getUTCSeconds();
var time = ( hh < 10 ? '0' + hh : hh ) + ':' + ( mm < 10 ? '0' + mm : mm ) + ':' + ( ss < 10 ? '0' + ss : ss );
$target.text( time );
var ms = now.getUTCMilliseconds();
setTimeout( function () {
showTime( $target );
}, 1100 - ms );
}
function liveClock() {
mw.util.addCSS( '#utcdate a { font-weight:bolder; font-size:120%; }' );
if ( !window.UTCLiveClockConfig ) {
UTCLiveClockConfig = {};
}
var portletId = UTCLiveClockConfig.portletId || 'p-personal';
var nextNode = UTCLiveClockConfig.nextNodeId ? document.getElementById( UTCLiveClockConfig.nextNodeId ) : undefined;
var node = mw.util.addPortletLink(
portletId,
mw.util.getUrl( null, { action: 'purge' } ),
'',
'utcdate',
null,
null,
nextNode
);
if ( !node ) {
return;
}
$( node ).on( 'click', function ( e ) {
new mw.Api().post( { action: 'purge', titles: mw.config.get( 'wgPageName' ) } ).then( function () {
location.reload();
}, function () {
mw.notify( 'Purge failed', { type: 'error' } );
} );
e.preventDefault();
} );
showTime( $( node ).find( 'a:first' ) );
}
$( liveClock );
} );
edit:
the way i originally fixed the problem is by putting a -7 in the hours section:
var hh = now.getUTCHours()-7;
It looks this is very simple Gadget limited to time in UTC. There are few options.
Find better script with support for time zones.
Write own script based on this one.
To write own script, there is critical part.
function get_PST_PDT_offset() {
/* You have to rewrite this function from time to time. */
var now = new Date();
var change = new Date(2016, 11, 5, 19, 0); /* 2016-11-06 2:00 PST */
if (now >= change) {
return -8;
} else {
return -7;
}
}
function showTime( $target ) {
var now = new Date();
var hh = now.getUTCHours();
var offset = get_PST_PDT_offset();
hh = (hh + offset + 24) % 24;
var mm = now.getUTCMinutes();
/* ... */
I'm trying to get server time at start and update it, cause i've to cotnrol some elements with real time. The problem is that if my serverTime doesn't have T the time is NaN on firefox and IE, but if i replace the empty space with T on chrome and IE i've a wrong time.
I now the work-around of replacing white space with T sucks but im outta of time :)
Thanks everybody
At start:
$tmpTime = date("Y-m-d H:i:s");
Head:
<script>
var serverTime = '<?=$tmpTime?>';
serverTime = serverTime.replace(" ", "T");
</script>
Script:
setInterval(function () {
console.log(serverTime);
var tmpTime = new Date(serverTime);
console.log(tmpTime);
var t = tmpTime.getTime();
t = t + 1000;
tmpTime = new Date(t);
serverTime = t;
if (tmpTime.getMinutes() < 10) {
var minutes = "0" + tmpTime.getMinutes();
} else {
var minutes = tmpTime.getMinutes();
};
newTime = tmpTime.getHours() + ":" + minutes;
$('#liveTime').text(newTime);
if ($("#program li[time-id='" + newTime + "'][class='alert']").length !== 0) {
alert("Lo streaming da te programmato sta per iniziare!");
$("#program li[time-id='" + newTime + "'][class='alert']").removeClass("alert");
}
titleToShow();
}, 1000);
function titleToShow() {
$("#program li").each(function () {
var prevTime = $(this).prev("li").attr("time-id");
var thisTime = $(this).attr("time-id");
var nextTime = $(this).next("li").attr("time-id");
currentTime = Date.parse('01/01/2011 ' + newTime);
prevTime = Date.parse('01/01/2011 ' + prevTime);
nextTime = Date.parse('01/01/2011 ' + nextTime);
thisTimeNew = Date.parse('01/01/2011 ' + thisTime);
if (currentTime >= thisTimeNew && currentTime < nextTime && currentTime > prevTime) {
title = $(this).find("p").text();
if (title != $("p#playingTitle").text()) {
$("p#playingTitle").text(title);
}
}
})
}
Don’t use a formated date, just pass the Unix timestamp value to the script (don’t forget to multiply it by 1000, because JS works with milliseconds).
var serverTime = <?php echo time(); ?>;
var tmpTime = new Date(serverTime * 1000);