I am learning some PHP. I have a script which checks to see if a JSON file exists. If it does not exist; it will populate it with some YQL and some data. If it exists, it will not do anything as it is better for cache and speed.
In my code; I have this line (currently only doing every 3 hours (10800)):
if ( !file_exists($cache) || filemtime($cache) < ( time() - 10800 ) ) {
What I want do is, despite the server time, I want to use the UK GMT timezone and check to see if it is 00.01 past midnight, if it is, that is when I want to update the script. Every day at 00.01 midnight in the UK. Now I have heard PHP supports timezone but I only want it on this script?
This is what I have tried.
// TIMEZONE
date_default_timezone_set("Europe/London");
$date = $date();
$timestr = $time();
$timestamp = strtotime('today midnight');
// VARS
$cache = '../media/js/data.json';
// VALIDATION
// -- The cache is new
if ( !file_exists($cache) || filemtime($cache) < ( time() - timestamp ) ) {
another approach would be as mentioned would be cron jobs. you mentioned you want uk time zone , in that case please set your php.ini time zone to UK. this is how you do it
//add this line or replace within your php.ini file
; Defines the default timezone used by the date functions
date.timezone = "Europe/London"
and then set the cron job.
I'm using some stuff like that
$timezone = "Your timezone";
$tmpTZ = date_default_timezone_get();
date_default_timezone_set($timezone);
// some code to generate the date
date_default_timezone_set($tmpTZ);
Putting that in a small function an your ready to go.
The easiest solution will be usage of Cron, just calculate the difference between 2 timezones, and add task on the calculated time
http://www.thegeekstuff.com/2009/06/15-practical-crontab-examples/
Related
I am using Laravel 4 and trying to calculate the difference of the Time on Server and the Time Save in Database in hours. Here is the code:
Time on Server=timeNowOnServer // 2016-02-03 19:05:43
Time saved in Database = setTime // 18:00:00
$timeNowOnServer = null;
$setTime = null;
$timeZone = $company->time_zone;
$company->save();
// My Time
$hour = substr($company->emp_auto_logout_time, 0, 2);
$setTime = Carbon::createFromTime($hour);
// Server Time Same as Mine
$timeNowOnServer = Carbon::now();
$timeNowOnServerSameAsMine = $timeNowOnServer->setTimezone($timeZone);
// Time Differnce Between SetTime and TimeOnServerSameAsMine
$timeDiff = $setTime->diffInHours($timeNowOnServerSameAsMine, $abs = false);
If Server Time is 14:00:00 for example and Set Time is 19:00:00. My time zone is GMT +5 Pakistan.
What I'm doing is, adding setting Server Time according to user time by giving time zone in the 3rd last line of the above given code.
When I use diffInHour it instead of giving me 0 it gives me -5 or 5. It means it's useing UTC (Server Time) and that's why give wrong difference in hours.
Can someone please let me know where I'm wrong?
You're trying to diff time in different time zones. A time difference (interval) is an absolute value, it doesn't depend on time zone. One second is always one second, be it UTC or Europe/Moscow.
Try without time zone (to be correct - using default server's time zone)
$timeDiff = $setTime->diffInHours($timeNowOnServer, $abs = false);
Always calc intervals using timestamps or the same time zone (doesn't matter exactly which one) for both DT values.
I need to send an email to users based wherever in the world at 9:00 am local time. The server is in the UK. What I can do is set up a time difference between each user and the server's time, which would then perfectly work if DST didn't exist.
Here's an example to illustrate it:
John works in New York, -5 hours from the server (UK) time
Richard works in London, UK, so 0 hour difference with the server.
When the server goes from GMT to GMT +1 (BST) at 2:00am on a certain Sunday, this means that John now has a -6H time difference now.
This scenario I can still handle by updating all the users outside the server's local time, but once I've moved forward/backward the time of all the other users, I still need a way to detect when (time and date) the users living outside the UK will (or will not) change their local time to a probable DST one.
I need a PHP method to know/detect when other parts of the world will enter/exit DST.
Do you need to know all the details of DST transition yourself? or do you just need to know when is 9:00 am in a given timezone?
If it's the latter, PHP can use your operating system's timezone database to do that for you. The strtotime() function is remarkably good at "figuring out" what you mean:
echo strtotime("today 9:00 am America/New_York"); // prints "1306501200"
echo strtotime("today 9:00 am Europe/London"); // prints "1306483200"
Just make sure you're using one of the PHP supported timezones.
As Jimmy points out you can use timezone transitions, but this is not available on PHP <5.3. as dateTimeZone() is PHP>=5.2.2 but getTransitions() with arguments is not! In that case here is a function that can give you timezone data, including whether in DST or not.
function timezonez($timezone = 'Europe/London'){
$tz = new DateTimeZone($timezone);
$transitions = $tz->getTransitions();
if (is_array($transitions)){
foreach ($transitions as $k => $t){
// look for current year
if (substr($t['time'],0,4) == date('Y')){
$trans = $t;
break;
}
}
}
return (isset($trans)) ? $trans : false;
}
Having said that, there is a simpler method using date() if you just need to know whether a timezone is in DST. For example if you want to know if UK is in DST you can do this:
date_default_timezone_set('Europe/London');
$bool = date('I'); // this will be 1 in DST or else 0
... or supply a timestamp as a second arg to date() if you want to specify a datetime other than your current server time.
Changing my answer a bit: DateTimeZone::getTransitions looks like it will do what you need, provided you have PHP >= 5.2.
From a comment in the documentation:
<?php
$theTime = time(); // specific date/time we're checking, in epoch seconds.
$tz = new DateTimeZone('America/Los_Angeles');
$transition = $tz->getTransitions($theTime, $theTime);
// only one array should be returned into $transition. Now get the data:
$offset = $transition[0]['offset'];
$abbr = $transition[0]['abbr'];
?>
So here, all we need to do is pass in the timezone we want to check and we can know if that timezone is in DST/what the offset is. You'll then need to check the offset against GMT to see if you want to send your e-mail now, or not now.
I created this PHP function to see if a time value is BST or not:
<?php
function isBST($timestamp)
{
$baseDate = date("m/d/Y H:i:s", $timestamp);
$clocktime=strtotime($baseDate." Europe/London")."\n";
$utctime=strtotime($baseDate." UTC")."\n";
//echo "$a \n$b \n";
if ($clocktime!=$utctime)
{
return true;
}
else
{
return false;
}
}
?>
I need to send an email to users based wherever in the world at 9:00 am local time. The server is in the UK. What I can do is set up a time difference between each user and the server's time, which would then perfectly work if DST didn't exist.
Here's an example to illustrate it:
John works in New York, -5 hours from the server (UK) time
Richard works in London, UK, so 0 hour difference with the server.
When the server goes from GMT to GMT +1 (BST) at 2:00am on a certain Sunday, this means that John now has a -6H time difference now.
This scenario I can still handle by updating all the users outside the server's local time, but once I've moved forward/backward the time of all the other users, I still need a way to detect when (time and date) the users living outside the UK will (or will not) change their local time to a probable DST one.
I need a PHP method to know/detect when other parts of the world will enter/exit DST.
Do you need to know all the details of DST transition yourself? or do you just need to know when is 9:00 am in a given timezone?
If it's the latter, PHP can use your operating system's timezone database to do that for you. The strtotime() function is remarkably good at "figuring out" what you mean:
echo strtotime("today 9:00 am America/New_York"); // prints "1306501200"
echo strtotime("today 9:00 am Europe/London"); // prints "1306483200"
Just make sure you're using one of the PHP supported timezones.
As Jimmy points out you can use timezone transitions, but this is not available on PHP <5.3. as dateTimeZone() is PHP>=5.2.2 but getTransitions() with arguments is not! In that case here is a function that can give you timezone data, including whether in DST or not.
function timezonez($timezone = 'Europe/London'){
$tz = new DateTimeZone($timezone);
$transitions = $tz->getTransitions();
if (is_array($transitions)){
foreach ($transitions as $k => $t){
// look for current year
if (substr($t['time'],0,4) == date('Y')){
$trans = $t;
break;
}
}
}
return (isset($trans)) ? $trans : false;
}
Having said that, there is a simpler method using date() if you just need to know whether a timezone is in DST. For example if you want to know if UK is in DST you can do this:
date_default_timezone_set('Europe/London');
$bool = date('I'); // this will be 1 in DST or else 0
... or supply a timestamp as a second arg to date() if you want to specify a datetime other than your current server time.
Changing my answer a bit: DateTimeZone::getTransitions looks like it will do what you need, provided you have PHP >= 5.2.
From a comment in the documentation:
<?php
$theTime = time(); // specific date/time we're checking, in epoch seconds.
$tz = new DateTimeZone('America/Los_Angeles');
$transition = $tz->getTransitions($theTime, $theTime);
// only one array should be returned into $transition. Now get the data:
$offset = $transition[0]['offset'];
$abbr = $transition[0]['abbr'];
?>
So here, all we need to do is pass in the timezone we want to check and we can know if that timezone is in DST/what the offset is. You'll then need to check the offset against GMT to see if you want to send your e-mail now, or not now.
I created this PHP function to see if a time value is BST or not:
<?php
function isBST($timestamp)
{
$baseDate = date("m/d/Y H:i:s", $timestamp);
$clocktime=strtotime($baseDate." Europe/London")."\n";
$utctime=strtotime($baseDate." UTC")."\n";
//echo "$a \n$b \n";
if ($clocktime!=$utctime)
{
return true;
}
else
{
return false;
}
}
?>
I need to compare two dates to show an edit link if it is within 5 mins after the post was made, in PHP. If more than 5 minutes have passed, don't show anything.
$answer_post_date = get_the_time("Y-m-d");
$current_date = date("Y-m-d");
$formated_current_date = strtotime($answer_post_date);
$formated_answer_post_date = strtotime($current_date);
At this point I have two values:
1274414400 ($formated_current_date)
1276056000 ($formated_answer_post_date)
I am not sure what to do next to check if the current date/time is > 5 mins from the answer post date.
Any suggestions would be great.
All I really need the answer to be is a Boolean (yes/no) and if yes, display the minuets left to show the link to edit.
You're only handling dates, how are you supposed to know if the difference is 5 minutes?
Anyway, I'd say the majority of the PHP code that uses the default PHP functions is at least somewhat broken. The problem is you, despite a unix timestamp storing the correct point in time something happens, it does not store timezone information. See here.
So, forget using only date and strtotime. Use the datetime extension.
Store in the database the Unix timestamp and the timezone (by timezone I mean e.g. Europe/Lisbon). Then:
$tz = new DateTimeZone($timezone);
$answer_post_date = new DateTime("$timestamp");
$answer_post_date->setTimeZone($tz);
$current_date = new DateTime("now", $tz);
$diff = $current_date->diff($answer_post_date);
if ($diff->format("a") > 0 ||
$diff->format("h") > 0 ||
$diff->format("m") >= 5) {
//more than 5 minutes have passed
}
Of course, for comparing dates, you can always compare the timestamps.
My understanding of what you need to do:
$delta = ($formated_current_date - $formated_answer_post_date) / 60; // in minutes
if ($delta < 5) {
// show $delta
}
EDIT: Like others pointed out, this alone will not fix all of the issues at hand. As I see it, the smallest change to your current code would be to use a date format with higher granularity - such as "Y-m-d H:i:s". This being enough, like others pointed out, is contingent on the post's date being in the same timezone as your system.
I don't see the need to do a round-trip to a string format and back, regardless of how efficient or reliable it is.
date() will default to calling time() which you can call directly and get the current time in seconds as a Unix epoch timestamp (which is what you're trying to end up with in $formated_answer_post_date). You need to look in the WordPress docs to find the equivalent based on the post's value.
Then you can do a simple comparison of seconds. 5 minutes is 300 seconds.
You will still need to check that the code can assume the timezones of both values will be the same.
I'm writing a PHP system and I need to get the system time. Not the GMT time or the time specific to a timezone, but the same system time that is used by the CRON system. I have a CRON job that runs every day at midnight and I want to show on a webpage how long will it take before it runs again.
For example:
Right now it is 6pm on my system clock. I run the code:
$timeLeftUntilMidnight = date("H:i", strtotime("tomorrow") - strtotime("now"));
The result, however, is "3:00" instead of "6:00". If I run
date("H:i", strtotime("tomorrow"));
It returns 0:00, which is correct. But if I run
date("H:i", strtotime("now"));
It returns 21:00, even though the correct should be 18:00.
Thanks.
There are many answers, however there is not even one correct at the time of writing.
PHP time() function doesn't return the system time, like most folks believe, but it return the PHP localtime, normally set with date.timezone in php.ini, or set with date_default_timezone_set() within a script.
For instance in one of my servers, PHP time was set to Europe/Romeand system time to UTC. I had a difference of one hour between system time and PHP time.
I'm going to give you a solution that works for Linux, I don't know for Windows. In Linux the system timezone is set in /etc/timezone. Now, this is normally outside my allowed open_basedir setting, but you can add :/etc/timezone to your list to be able to read the file.
Then, on top of the scripts, that want to get the system time, you can call a library function that sets the script timezone to the system timezone. I suppose that this function is part of a class, so I use static:
static function setSystemTz() {
$systemTz = trim(file_get_contents("/etc/timezone"));
if ($systemTz == 'Etc/UTC') $systemTz = 'UTC';
date_default_timezone_set($systemTz);
}
To make the matter worse in PHP 5.3.3 'Etc/UTC' is not recognized, while 'UTC' is, so I had to add an if to fix that.
Now you can happily call time() and it will really give you the system time. I've tested it, because I needed it for myself, that's why I found this question now.
php's time will return the system time. you can format it with date
if you just want to display the time in the local time of the visitor maybe you're better off using a little javascript
This is the easiest and most foolproof way to do it:
$sys_timestamp = strtotime(exec("date"));
Let's not try to spoof it with php, let's just get the real sys time ;)
(Will work on any unix based system)
time()
will give you the current system timestamp.
Manual
Returns the current time measured in the number of seconds since the Unix Epoch (January 1 1970 00:00:00 GMT).
You can get the date/time of the server on which PHP is running using the time() function -- it'll return a timestamp, that corresponds to the current datetime.
It's the system time, on that server -- the same as used by cron.
If you want the GMT time you may want to use gmtstrftime(), which will give you the system time but as in GMT. There's more info at http://us2.php.net/gmstrftime.
If you are after a formatted date:
date ('d/m/y h:i:s');
will do the trick, there is no need to pass time() into date as it will default to the current system time if no second parameter is supplied.
for more formatting options see here: http://php.net/manual/en/function.date.php
Otherwise you can just use
time()
To get you the current unix timestamp as others have mentioned.
For getting the current time of your system you need to set the correct date.timezone in your php.ini file. For example if you are from India then you would write:
date.timezone = Asia/Calcutta
For Germany, it would be:
date.timezone = Europe/Berlin
After doing this, date("Y-m-d H:i:s") will give your current time. For getting your timezone see the list of timezones supported by PHP.
try this one:
$time=date("h:i:s A", strtotime("now"-14));
echo $time;
You can adjust the time by changing the number 14 above.
You can current local time via below Javascript and set it in any PHP variable than.
<script>
// For 24 hours
var ct = new Date();
var hr = ct.getHours();
var mt = ct.getMinutes();
if (mt < 10) {
mt = "0" + mt;
}
document.write("<b>" + hr + ":" + mt + " " + "</b>");
// For 12 hours (AM / PM)
var ct = new Date();
var hr = ct.getHours();
var mt = ct.getMinutes();
var ampm = "AM";
if (hr >= 12) {
ampm = "PM";
hr = hr - 12;
}
if (hr == 0) {
hr = 12;
}
if (mt < 10) {
mt = "0" + mt;
}
document.write("<b>" + hr + ":" + mt + " " + ampm + "</b>");
</script>