I am trying to show ticker clock for different timezone. When I looked around the web, it looks like it takes number for the offset(for example +5.5 hours) in javascript. But the way we are getting the gmtformat is +05:30 in php which I am trying to feed in to the javascript function. Is there any function that I can use to convert?
/*CLOCK CODE IN JAVASCRIPT*/
function startclock(field, timediff, newOrRepeat)
{
var clockAction=newOrRepeat;
if (timediff=="") {$(field).html("-------");return false;}
/****THERE ARE MORE STUFF IN BETWEEN AND AFTER WHICH IS NOT RELEVANT TO OFFSET****/
var secondsDiff=0;
var secondsTimeZone = 0;
//calculate the difference in time set by both the timezone as well as the DST
secondsTimeZone = parseInt(timediff);
if ($("input[name='daylight']:checked").val()=="on" && $(field).siblings("#isDaylight").val()=="no")
secondsDiff=secondsTimeZone + 3600;
else if ($("input[name='daylight']:checked").val()=="off" && $(field).siblings("#isDaylight").val()=="yes")
secondsDiff=secondsTimeZone - 3600;
else
secondsDiff = secondsTimeZone;
var thetime=new Date();
thetime.setUTCSeconds(parseInt(thetime.getUTCSeconds())+parseInt(secondsDiff));
var nhours=thetime.getUTCHours();
var nmins=thetime.getUTCMinutes();
var nsecn=thetime.getUTCSeconds();
}
I am getting getting gmt format straight from php which i am passing to this function.
function convert_time($time){
$parts = explode(':', $time);
return $parts[0] + number_format($parts[1]/60, 2);
}
Related
Hello I need to spend a given XML through javascript to subtract the current date and time date.
What makes this code is to show the remaining time of a song streaming in minutes and seconds
And then with javascript parsing date and I transform in milliseconds and the current date will also rest in ms.
In Chrome date shows me perfectly, but in Mozilla and IE NaN console shows me and gives error.
I do not understand is that if I have parsed the date because it only works in Chrome. There must be a mistake.
PHP (I draw the start date of a song)
<?php
$xml = # simplexml_load_file('http://www.example.com');
foreach ($xml as $track){
$startTime = $track->starttime;
$songDuration = $track->playduration;
}
?>
JAVASCRIPT:
var spend javascript
var tiempoComienzo= "<?php echo $startTime ?>";
var cancionDuracion="<?php echo $songDuration ?>";
//parse delivered date from php
var d = new Date(Date.parse(tiempoComienzo));
//PHP get the date in milliseconds
var resultPHPms = d.getTime();
//get the current date
var f = new Date();
//step the current date to milliseconds
var resultJSms = f.getTime();
//adding the date of the song to the length of the song
var inicioMasCancion=parseInt(cancionDuracion) + parseInt(resultPHPms);
//It is the challenge to the current date
var TiempoRestante=inicioMasCancion-parseInt(resultJSms);
//pass the result to seconds
seconds=(TiempoRestante/1000)
var container = document.getElementById('time');
var seconds = parseInt(seconds+7);
//step seconds to minutes and seconds
var minutes = parseInt( seconds / 60 ) % 60;
var seconds = seconds % 60;
var contadorDeTiempo=(minutes < 10 ? "0" + minutes : minutes) + ":" + (seconds < 10 ? "0" + seconds : seconds);
countdown(seconds);
function countdown:
<script>
var timer;
function countdown(seconds) {
seconds--;
if(seconds >= -1) {
container.innerHTML =contadorDeTiempo;
}
}
timer = setInterval(countdown, 1000);
</script>
HTML:
<span id='time'></span>
In chrome it is perfectly displayed and works perfect. But in Mozilla and IE console NaN it is shown, specifically in this line:
var d = new Date(Date.parse(tiempoComienzo));
How I could solve? The resulting XML date is as follows:
2015-12-20 12:45:33.17
thanks very much for your help
This project includes creating a form for users to enter the start and end time of a promotion. The site where the promotion will be live operates in the Pacific Time Zone and the user creating the promotion could be anywhere in the world.
The start time must be one hour greater than the current PST (or PDT depending on season). The current method of validating the start time is not working because it pulls the local time of the user's computer.
I need a way to compare the user's local time to Pacific Time and validate that the promotional start time is one hour greater.
My working theory is to find the offset between the user's local time and GMT time, then find the offset between current Pacific time and GMT (which varies by 7 or 8 hours depending on DST--right?), then apply these offsets to the user's time and compare to Pacific time plus one hour.
I have succeeded in finding the necessary offsets and alerting the correct current time in Pacific time in various strings and timestamps but the overall logic escapes me. Also, I have been unable to successfully add one hour to a TimeStamp.
this question is similar, and many others, but in this case the OP has a fixed offset:
Compare user's time zone with the website's office location time zone
Current code:
function valid() {
var starttime=$('#1-PromotionalSaleStartTime').val();
var endtime=$('#1-PromotionalSaleEndTime').val();
var now = new Date();
var hour= now.getHours();
var min = now.getMinutes()+10;
var nows= parseInt(hour)+1;
var time=nows+':'+min;
var presentime = now.getHours()+':'+now.getMinutes()
var month =now.getMonth()+1;
var day = now.getDate();
var output = (month<10 ? '0' : '') + month + '/' +(day<10 ? '0' : '') + day + '/' + now.getFullYear() + ' '+time;
var now = (month<10 ? '0' : '') + month + '/' +(day<10 ? '0' : '') + day + '/' + now.getFullYear() + ' '+presentime;
var present = new Date(now);
var oneDay = 24*60*60*1000; // hours*min*sec*milliseconds
var firstDate = new Date(starttime);
var secondDate = new Date(endtime);
var diffDays = Math.round(Math.abs((firstDate.getTime() - secondDate.getTime())/(oneDay)));
var diff = Math.round(Math.abs(( present.getTime() - firstDate.getTime())/(oneDay)));
var presentTimeStamp = +'<?php echo time(); ?>' * 1000;
var firstDateTimeStamp = Date.parse($('#1-PromotionalSaleStartTime').val());
var err = 0;
<?php if($this->add!="" && isset($this->add)) {?>
if(presentTimeStamp > firstDateTimeStamp) {
$('#1-PromotionalSaleStartTime').after('<ul class="errors"><li>Sorry, but you cannot add past date.</li></ul>');
err++;
}
<?php } ?>
if(diffDays==0){
$('#1-PromotionalSaleEndTime').after('<ul class="errors"><li>The date difference between Start and End dates should be 24 hours.</li></ul>');
err++;
}
if(starttime < output){
$('#1-PromotionalSaleStartTime').after('<ul class="errors"><li>Your Start time should be at least 1 hour more than the current Pacific Time like. '+ output +'</li></ul>');
err++;
}
if((Date.parse(starttime)> Date.parse(endtime)) ){
$('#1-PromotionalSaleEndTime').after('<ul class="errors"><li>End Time cannot be less than Start Time plus 1 day.</li></ul>');
err++;
}
Try this on the Server side:
/* timetest.php */
<?php
if(isset($_POST['dateInfo'])){
date_default_timezone_set('America/Los_Angeles'); $data = array();
$dt = new DateTime;
$pacificPlusOneOffset = dt->add(new DateInterval('P1D'))->getOffset();
$data['diff'] = +$_POST['dateInfo']-$pacificPlusOneOffset;
echo json_encode($data);
}
else{
// could be some kind of hack
}
?>
AJAX should send JavaScript on the Client side, like:
var pre = onload;
onload = function(){
if(pre)pre();
// more code to run other code here
function post(url, send, success){
var x = new XMLHttpRequest || new ActiveXObject('Microsoft.XMLHTTP'), ec = [], s;
for(var i in send){
ec.push(encodeURIComponent(i)+'='+encodeURIComponent(send[i]));
}
s = ec.join('&').replace(/%20/g, '+'); x.open('POST', url);
x.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
x.setRequestHeader('Content-length', s.length);
x.setRequestHeader('Connection', 'close');
x.onreadystatechange = function(){
if(x.readyState === 4 && x.status === 200 && success){
success(eval('('+x.responseText+')'));
}
}
x.send(s);
}
post('timetest.php', {dateInfo:new Date().getTimezoneOffset()}, function(result){
console.log(result.diff);
})
}
I am trying to create a Javascript clock that will display the current Actual time, rather than displaying the local time of the client machine.
The clock is part of a script which calculates the difference in time between two values (in php but the purpose of this clock is to give a visual representation). It is important that the user of the script cannot change the time that is displayed as this will produce incorrect results for the outcome of the whole program.
I realise that i may have to use a php function to return the time in a particular time zone but i do not understand how to input this into my script. My Javascript clock code is below (currenttime_large is the ID of the DIV container of this script) :
<script type="text/javascript" language="javascript">
function renderTime() {
var currentTime = new Date();
var h = currentTime.getHours();
var m = currentTime.getMinutes();
var s = currentTime.getSeconds();
setTimeout('renderTime()',1000);
if (h == 0) {
h = 12;
}
if (h < 10) {
h = "0" + h;
}
if (m < 10) {
m = "0" + m;
}
if (s < 10) {
s = "0" + s;
}
var myClock = document.getElementById('currenttime_large');
myClock.textContent = h + ":" + m + ":" + s + " ";
myClock.innerText = h + ":" + m + ":" + s + " ";
}
renderTime();
</script>
Please could someone advise how this script can be adjusted so that the clock which is displayed, displays GMT(London) time rather than the client time.
Many thanks in advance,
Aidan
Use the getUTC... methods:
var h = currentTime.getUTCHours();
var m = currentTime.getUTCMinutes();
var s = currentTime.getUTCSeconds();
I've been looking over something like this,
The best solution I've found is this
http://www.jqueryscript.net/demo/jQuery-Based-Analog-And-Digital-World-Clock-jClocksGMT-js/
If you want you can save the whole page, or download necessary files if they not saved automatically. Then in your html code you just change the GMT timezone according to ID.
That's it
I was searching of world analog clock. i found one source/example which is basically cretated with jQuery, Html 5, CSS 3 and canvas.
Source : https://github.com/php-dedicated-developers/world-clock
It can be done without PHP. I ve done it using simple HTML and JavaScript calculations.
Note: This clock IS NOT UNIVERSAL.
Because i live in india, i fixed all parameters according to Indian GMT (5:30).
If someone wants to use it who does not live in India will have to customize parameters according their own country GMT
How my code works? Here is your answer
First we have created a simple timer program.
Passed the time argument to a function called london()
3.in function london() everything is processed. I have put GMT of India. using the parameters function london is producing correct London time from Indian time and given GMT time
Note:
1. As this code is not universal.. people out of India will have to customize it as they want...
2.This code uses device time and processes correct GMT 0 time. Example my code works substracting 5 hours and 30 minutes from device time because my GMT is 5:30 (India)
3.Will work fine offline
4.If someone changes country(GMT) they will have to customize code again
Full Code
<body onload="timer()">
<p id="txt1"></p>
<p id="txt2"></p>
<script>
function timer(){
//Getting Device Time
var today = new Date();
var h = today.getHours();
var m = today.getMinutes();
var s = today.getSeconds();
//Returning value of ckeckTime();
m = checkTime(m);
h = checkTime(h);
s = checkTime(s);
var trigger = setTimeout(timer,1000);
document.getElementById("txt1").innerHTML = h+" "+m+" "+s;
london(h,m,s); //Passing device time to function london
}
function london(h,m,s){
//This function produces london time
//var h (Device hour)
// m (Device minute)
// s (Device second)
defhr = 5; //define hour
defmn = 30; //define minutes
/* defhr = 5 and defmn = 30 according to India GMT +5 30*/
if(m < defmn){ //When device minute is less than define minutes
defhr += +0
var hour = h - defhr;
let x = m - defmn;
var min = 60 + x;
} else {
defhr += -1
var hour = h - defhr;
var min = m - defmn;
}
if(h < defhr){ //When device hour is less than define hour
let y = defhr - h;
var hour = 24 - y;
}else {
var hour = h - defhr;
}
// returning value of checkTime();
hour = checkTime(hour);
min = checkTime(min);
document.getElementById("txt2").innerHTML = hour+" "+min+" "+s;
}
//checkTime function adds 0 in front a number when it is less than 10
function checkTime(i){
if(i<10){ i="0"+i; }
return i;
}
</script>
</body>
</html>
Tip:
1. If you live in western countries or GMT value is negative then put negative value in defhr and defmn section.
If anyone is using this code in GMT + 5:30 (India)
They will not need customization.
Make sure your code is producing correct London GMT time.. Grab notebook,calculator or you can test it with online world clock too
How can I get the time of the client side?
When I use date() it returns server's time.
Here's a "PHP" solution:
echo '<script type="text/javascript">
var x = new Date()
document.write(x)
</script>';
As mentioned by everyone PHP only displays server side time.
For client side, you would need Javascript, something like the following should do the trick.
var currentTime = new Date();
var hours = currentTime.getHours();
var minutes = currentTime.getMinutes();
if (minutes < 10) {
minutes = "0" + minutes;
}
document.write("<b>" + hours + ":" + minutes + " " + "</b>");
And if you want the AM/PM suffix, something like the following should work:
var currentTime = new Date();
var hours = currentTime.getHours();
var minutes = currentTime.getMinutes();
var suffix = "AM";
if (hours >= 12) {
suffix = "PM";
hours = hours - 12;
}
if (hours == 0) {
hours = 12;
}
if (minutes < 10) {
minutes = "0" + minutes;
}
document.write("<b>" + hours + ":" + minutes + " " + suffix + "</b>");
Here is a list of additional JavaScript Date and Time functions you could mess around with.
You could possibly use Geolocation by IP Address to work out which country the user is in, and then use that.
But using Javascript or letting the user choose a Timezone will probably be better.
As PHP runs on the server-side, you cannot access the client-side time from PHP : PHP doesn't know much about the browser -- and you can have PHP scripts that run without being called from a browser.
But you could get it from Javascript (which is executed on the client-side), and, then, pass it to PHP via an Ajax request, for example.
And here are a couple of questions+answers that might help you getting started :
Automatically detect user’s current local time with JavaScript or PHP
How can I determine a web user’s time zone?
PHP is server side only as far as i know.
You maybe want to use JavaScript.
As other's have mentioned, you can use Geo Location Services based on the IP Address.
I found it to be off by about 18 seconds due to IP location accuracy, by using a $responseTime offset it helped me narrow it down to 2 second accuracy in the Viewers Location.
<?php;
echo deviceTime('D, M d Y h:i:s a');
function deviceTime($dateFormatString)
{
$responseTime = 21;
$ip = (isset($_SERVER["HTTP_CF_CONNECTING_IP"])?$_SERVER["HTTP_CF_CONNECTING_IP"]:$_SERVER['REMOTE_ADDR']);
$ch = file_get_contents('https://ipapi.co/'.$viewersIP.'/json/');
$ipParts = json_decode($ch,true);
$timezone = $ipParts['timezone'];
$date = new DateTime(date('m/d/Y h:i:s a', time()+$responseTime));
$date->setTimezone(new DateTimeZone($timezone));
return $date->format($dateFormatString);
}
?>
I was wondering what the best way is to calculate the difference in time from now to a certain point, let's say the countdown time.
I have an auction that has a closetime at a certain point, this time is stored in a MySQL record in the format " DATETIME 00-00-000 00:00:00 ". This record is called closetime.
Now on my website I have JavaScript code that gets this time via a PHP file. The JavaScript loops every second using setInterval 1000. The PHP file gets the closetime from the db, and sends it back in this format
strtotime($result['closetime']);
And I get the time of the request, I want to use the server time, and not the time in JavaScript, because the clock of the user can be off.
strtotime(date("H:i:s", $_SERVER['REQUEST_TIME']))
I send back these two timestamps and calculate the time difference between them in JavaScript. I use this function to do it, the values send back from PHP I call currentTime and closeTime, I think this should be clear.
function auctionDelayTime(currentTime,closeTime){
totaldelay = closeTime - currentTime;
if(totaldelay <= 0){
return 'ended';
}else{
if( days=parseInt((Math.floor(totaldelay/86400))) )
totaldelay = totaldelay % 86400;
if( hours=parseInt((Math.floor(totaldelay/3600))) )
totaldelay = totaldelay % 3600;
if( minutes=parseInt((Math.floor(totaldelay/60))) )
totaldelay = totaldelay % 60;
if( seconds=parseInt((Math.floor(totaldelay/1))) )
totaldelay = totaldelay % 1;
return hours+':'+formatTimes(minutes)+':'+formatTimes(seconds);
}
}
function formatTimes(value){
return value < 10 ? '0'+value : value;
}
I think this is an awful lot of code do something so simple. Does anyone have a better solution or maybe more 'beautiful' code.
Enjoy!
There is a jquery Countdown Plugin that supports server sync through AJAX:
From the docs:
Synchronise the client's time with
that of the server by providing a
function that returns the current
server date and time. This date and
time should take into account the
server's timezone and any difference
between that time and the client's is
applied to the countdown when it is
started or changed.
The following example uses a PHP
program on the server to return the
current server time in a format that
can be used directly by the JavaScript
callback. You should make sure that
your server call is synchronous.
$(selector).countdown({
until:liftoffTime, serverSync: serverTime});
function serverTime() {
var time = null;
$.ajax({url: 'http://myserver.com/serverTime.php',
async: false, dataType: 'text',
success: function(text) {
time = new Date(text);
}, error: function(http, message, exc) {
time = new Date();
}});
return time;
}
serverTime.php:
<?php
$now = new DateTime();
echo $now->format("M j, Y H:i:s O")."\n";
?>
Use Date object.
var d = new Date(difference_in_milliseconds);
var seconds = d.getSeconds();
var minutes = d.getMinutes();
var hours = d.getHours() - 1; //See note
Note: Strangely, hours value is bigger by one than I would expect for reason I don't understand. It looks like "midnight Jan 1, 1970" was at 1 AM :-)
UPDATE: The difference of 1 is due to the offset of my timezone (GMT +1).
Slight change that will solve this:
var d = new Date();
var offset = d.getTimezoneOffset() * 60000;
var d = new Date(difference_in_milliseconds + offset);
var seconds = d.getSeconds();
var minutes = d.getMinutes();
var hours = d.getHours();
This JavaScript library is easy to use and will likely serve you well.
Why not have the php page give you the difference?
$sql = "SELECT UNIX_TIMESTAMP(NOW()) as currentTime, UNIX_TIMESTAMP(closeTime) as closeTime FROM yourTable WHERE yourRecordId = '123'";
$query = mysql_query($sql);
$result = mysql_fetch_assoc($query);
echo timeRemaining($result['currentTime'], $result['closeTime']);
function timeRemaining($start, $end) {
$dateDiff = $end - $start;
if ($dateDiff <= 0) { return 'Ended'; }
$fullDays = floor($dateDiff/(60*60*24));
$fullHours = floor(($dateDiff-($fullDays*60*60*24))/(60*60));
$fullMinutes = floor(($dateDiff-($fullDays*60*60*24)-($fullHours*60*60))/60);
return "Ending in $fullDays days, $fullHours hours and $fullMinutes minutes.";
}
Do you really have to get the time through AJAX every 1000 ms?
(i suppose that you're hoping for closetime changes? ...)
But if you really must do it this way, i'd suggest getting the time difference directly in MySQL for code simplicity.
$sql = "SELECT TIMEDIFF(NOW(), `CreateTime`) from `Table` WHERE `id`=1;"