Get milliseconds independent from system date/time in PHP - php

I need to get the current(!) milliseconds for a custom timer-implmentation, but the milliseconds have to be independent from the actual system date/time:
When ever the system date/time is set to a new value (e.g. NTP-Update), the running(!) script should not be affected:
$t=microtime(true);
while ( ($t+100) < microtime(true) ) {
...
}
This loop is just waiting for 100 seconds. But what happens, when the user (or system) sets a new system date/time while the loop is running? Then the code would run into problems, because microtime() gives an absolute value - not a relative amount of milliseconds.
What I need is a (system-wide) function that tells me a system-date/time-independent value of milliseconds, e.g. milliseconds since boot-up.
Any idea?

Related

php while loop where functions are ran based on time of day

I have created two functions in a separate php file and want them to run over and over.
After function A completes, I want it to compare the current time, relative to the last time function B ran, and if more than 24hrs has elapsed (or whatever value I set it to), it runs function B, resets the next time for when it should be trigger to run, and continues to run function A. They need to run separately and not parallel since values altered in function A will affect function B and thus need to be separate. The ideal scenario is I have a config.php file where I set the time delay (in hours), but I can sort that out later!
I am stumped on how to get this while(true){} loop organized... any ideas?
Regardless of whether you end up doing it this way (because I think the comments about cron make some good points, and there are some other issues you may run into with a continuously running PHP script like this) here's a basic logic for executing the alternate function based on a defined delay.
// define the delay and initialize the timestamp
$delay = 86400; // 24 hours, for example
$last_time = time();
while (true) {
functionA();
// the next time functionB should execute is the timestamp for the last run + the delay
if (time() > $last_time + $delay) {
functionB();
$last_time = time(); // reset the timestamp
}
}
Would something of this nature be similar to what you're looking for?
while ($time > 13 && $time < 21)
You could have flags involved in each function as well. If a boolean flag is fired and is = 1, then continue on?

Adding 2 different timestamp and dealing with PHP Datetime class

I'm building an application that shows specific times on a given day. This application is meant to serve ppl worldwide.
I do all the calculation with a TZ in an hour format (-4 / 2 / 9.5 / -1 ETC). (don't worry. the hour tz is after DST calculations)
Now, I would like to show the user his local time. due to dev reasons, i can use only the hour tz for this calculation.
after a lot of tries, i maneged to write a piece of code that seems to work. (tested it for few timezones, negetive and positive)
I am wondering if my code is ok? could i do it in a more efficent way? do this code support infinite date range?
here is the code:
static function current_local_time_zmanim($tz)
/*
* This function will get the number of hours off set (the time zone that Full_Zmanim_calculation() is using to make the calcukation) and will return the current local time and date.
*/ {
$tz= ($tz * 3600);// calculatoin: (hour offset(tz. can be -4 or 4) * 3600). eg: (-4*3600) or (3*3600)// converting the hour tz to TIMESTAMP
$date_utc = new DateTime(null, new DateTimeZone("UTC")); // current time in UTC.
$utctime= $date_utc->getTimestamp(); // current time in UTC TIMESTAMP
$date_utc->setTimestamp($utctime + ($tz));// keep in mind that tz can be either positive or negetive
$localtime= $date_utc->format('H:i');
echo "<br> local time: $localtime <br> ";
return $localtime;
}
What do you think?
Thanks!

PHP server side incremental counter

sorry I am new to PHP and need some help/guidance on creating a counter that will work server side, so I guess update an initial value?
I need for example to start with a base number of 1500 and have that number increase by 1 every 2 minutes, obviously so any visitors will see an increased number each time the visit.
Would the initial value need to be stored in sql or can a txt file be updated?
Any help would be great,
Thanks
It can be done in SQL if you want it but a text file is OK too, just save a value (1500), then create a cronjob and let it execute a PHP file where you'll have to set up the code that executes an SQL query which updates that value OR the code to update that text file every 2 minutes.
Example:
# Every two minutes
*/2 * * * * /your/path/too/this/file/updatecode.php
In your PHP file:
$SQL = "UPDATE table SET columnname = columname + 1";
// etc...
// OR the text file update code
If you don't need to store it specifically for some reason, then you don't need to run cron etc... Take a time stamp of a specific point in time you want to start at. Then calculate minutes since and add it to your start number (1500)
//Start Number
$n = 1500;
$cur_time = time();
$orig_time = strtotime("2013-10-21 10:00:00");
//New Number + difference in minutes (120 seconds for 2 mins) since start time
$newn = $n + round(abs($cur_time - $orig_time) / 120,0);
// Output New Number
echo $newn;
And if you wanted it in one line for copy/paste
echo 1500 + round(abs(time() - strtotime("2013-10-21 10:00:00")) / 120,0);
You could do this without a database just using dates. work out the difference in time between two dates (the current date and the starting date when you created the script), then divide that down into the correct amount of milliseconds for 2 minutes, and add that to your initial 1500.
If storing it is needed a SQL database for this is probably overkill.
Create you number, serialize it and store it to a file. Load it from the file next time, unserialize, increment, serialize and save.
You can save a time stamp along with the number to the file to avoid having to run some job every 2 minutes and instead calculate the correct value when you load the number back from the file.
Something like this (but error checking etc should be added and I haven't actually tried it to make sure the calculation is correct... but the main idea should be visible).
<?php
if(file_exists('mydatafile')) {
$data = unserialize(file_get_contents('mydatafile'));
// Calculate correct value based on time stamp
$data['number'] += round((time() - $data['timestamp']) / 120);
}
else {
// Init the number
$data["number"] = 1500;
}
// Print it if you need to here
// Update time stamp
$data["timestamp"] = time();
// Serialize and save data
file_put_contents('mydatafile', serialize($data)));

javascript function new Date() not working

My problem is as follows:
I want to display nepalese standard time in my website,so i set default timezone of my
website to 'Asia/kathmandu' using command: php_value date.timezone 'Asia/kathmandu' in htaccess file.
when i display time using any php functions like strftime() or date() ,it shows the nepalese standard time,
But when i use javascript function new Date(<?php echo time()*1000; ?>),it displays
the time of my personal pc i am using to view my website.
How can i display correct time using javascript date functions? Can anybody help me out?
Your issue is because javascript (actually ECMAScript) date objects are based on a UTC time value. When you do:
new Date(<?php echo time()*1000; ?>)
you are passing a UTC millisecond time value to the Date constructor, which then creates a date object. When you use the usual Date methods to format a string, or use Date.prototpye.toString or Date.prototype.toLocaleString, you will get a string based on the client's locale. Note that all these strings are implementation dependent and vary widely for the locale version.
If you want the timezone of the server, then use the server to set it. Or you can send a time zone offset in minutes to be applied to the local time to get back to Nepalese Standard Time (UTC + 5:45). Note that in ECMAScript, the time zone offset is minutes to be added to the local time to get UTC, whereas it is more normal to define the offset in minutes to be added to UTC to get the local time.
So to get NST:
function toNST(timeValue) {
function z(n) {return (n<10? '0' : '') + n}
var d = new Date();
var nstOffset = 5 * 60 + 45;
d.setMinutes(d.getMinutes() + d.getTimezoneOffset() + nstOffset);
return z(d.getHours()) + ':' + z(d.getMinutes()) + ':' + z(d.getSeconds());
}
alert(toNST(+(new Date()))); // about 11:07:17 at the moment
Use
new Date(Date.NPT(year, month, day, hour, minute, second))
Call the time via ajax from your server. That has the advantage of a better code maintanance. If you change the time again (e.g. if you want to use the code for another location) you have only to change the time in .haccess.

How to supply a value to the javascript method Date.setTime() from PHP?

Is it time()?
Is it time().substr(microtime(), 2, 2)?
Is it time().substr(microtime(), 2, 3)?
Kind of lost with the following snippet.
function updateClock ( ) {
var timeStamp = <?php echo time().substr(microtime(), 2, 2);?>;
var currentTime = new Date ( );
currentTime.setTime( timeStamp );
...
...
}
My goal is to use server time and start ticking from there on client browser window. The code above either returns the current client computer time or sometime in 1973. I guess I'm not getting the right time stamp format for setTime()?
Thanks!
1000
I tried that but the web page still shows my local time after I upload the js.php (rendering the javascript code) to my server. My server is approx 12 hours different in time from me. My guess is that does php takes client side time into account running time() ? I mean browsers do send request time to apache right?
I copied the time() * 1000 returned value from the web page run on my server and pasted it into a local page:
<script type="text/javascript">
var d = new Date();
d.setTime(1233760568000);
document.write(d);
</script>
And it's indeed my local time. Thus the guess.
Is there anyway to specify time zone for time()?
Date.setTime expects the number of milliseconds since 1970-1-1. php's time function yields the number of seconds since 1970-1-1. Therefore, you can just use
var TimeStamp = <?php echo time()*1000;?>
Due to latency issues (the browsers needs to load the whole page before starting JavaScript), the time will usually drift one or a couple of seconds though.
Multiply by 1000. JavaScript expects milliseconds while PHP returns seconds.
Date.setTime() wants milliseconds since the Unix Epoch, and time() returns seconds since then. If absolute precision isn't required (and given your methodology, I don't think it is), just multiply the value you get from time() by 1000.
Edit: beaten twice--D'oh

Categories