i am using following codes to get current time on server as per timezone parameter but i am getting wrong output. About 10/20 minutes delay then server time. And it also not gets updated. How to solve it? any idea?
<?php
function server_time_as_per_users_zone($users_zone){
$dateTime = new DateTime('now', new DateTimeZone($users_zone));
$r = $dateTime->format("d-m-Y h:m A");
return $r;
}
echo server_time_as_per_users_zone("Asia/Dhaka");
You are using a wrong format mask. The m stands for month number and not minutes.
Change it to
function server_time_as_per_users_zone($users_zone){
$dateTime = new DateTime('now', new DateTimeZone($users_zone));
$r = $dateTime->format("d-m-Y h:i A");
return $r;
}
echo 'UTC - ' . server_time_as_per_users_zone("UTC").PHP_EOL;
echo 'Europe/London - ' . server_time_as_per_users_zone("Europe/London").PHP_EOL;
echo 'Asia/Dhaka - ' . server_time_as_per_users_zone("Asia/Dhaka").PHP_EOL;
RESULT:
UTC - 19-04-2017 05:40:23 PM
Europe/London - 19-04-2017 06:40:23 PM
Asia/Dhaka - 19-04-2017 11:40:23 PM
Related
I'm having trouble calculating the number of hours worked.
We start with a time which starts as a string in this case ($time).
Then we change the time to 00:00:00 and store the result as a new variable ($newtime).
Then we need to calculate the difference between $time and $newtime but there is a formatting issue which I do not fully understand. Would anyone help?
$time = "2017-09-01 11:00:00"; //must start as a string like this
$newtime = new DateTime($time);
$newtime->setTime(00, 00,00); //change time to 00:00:00
$worktime = round((strtotime($time) - $newtime)/3600, 2);
echo "Hours Worked: " . $worktime . "<br>";
You're subtracting a timestamp with a DateTime object, so it tries to convert the DateTime object to an int, which it can't. You need to get the timestamp for the DateTime object, to subtract two ints:
<?php
$time = "2017-09-01 11:00:00"; //must start as a string like this
$newtime = new DateTime($time);
$newtime->setTime(00, 00,00); //change time to 00:00:00
$worktime = round((strtotime($time) - $newtime->getTimestamp())/3600, 2); // notice the $newtime->getTimestamp() call
echo "Hours Worked: " . $worktime . "<br>";
Demo
DateTime::getTimestamp() reference
You are mixing types (trying to cast object to int)... And maybe you didn't realize about the error you are making because you have disabled errors.
Please use, the method that Datetime class brings to you:
http://php.net/manual/es/datetime.gettimestamp.php
You can do it in both ways:
$newtime->getTimestamp()
or by using this:
date_timestamp_get($newtime)
As this:
$time = "2017-09-01 11:00:00"; //must start as a string like this
$newtime = new DateTime($time);
$newtime->setTime(00, 00,00); //change time to 00:00:00
$worktime = round((strtotime($time) - date_timestamp_get($newtime))/3600, 2);
echo "Hours Worked: " . $worktime . "<br>";
Please, be free of using this: http://sandbox.onlinephpfunctions.com/code/f78c993f709a67ac2770d78bb809e68e3a679707
I am trying to check if in a database the time of a row and a certain column is older then today then to echo success but it is echoing success for a date which is tomorrows!
Code
// Set variable for the time
$timenow = date('l jS \of F Y h:i:s A');
// Start Expired password check and drop function
function cronexec_expired ($timenow) {
include('../../config.php');
// Open up a new MySQLi connection to the MySQL database
mysql_connect($dbHost, $dbUsername, $dbPassword);
mysql_select_db($dbTable);
// Query to check the status of the code input
$expiry_check = "SELECT * FROM code_log WHERE status='Unused'";
// Run the query
$expiry_checkexec = mysql_query($expiry_check);
while($expiry_possibles = mysql_fetch_array($expiry_checkexec)) {
echo $expiry_possibles[6] . '<br /><br />';
echo $timenow . '<br /><br />';
if (date('l jS \of F Y h:i:s A', strtotime($expiry_possibles[6]) < $timenow)) {
echo "Success";
}
}
}
$expiry_possibles[6] value
Monday 9th of September 2013 12:46:20 PM
Time Now
Sunday 8th of September 2013 01:35:22 PM
Any advice would be appreciated
I don't see why you are using a full length date, there is no need. Instead how about using the unix timestamp? See http://php.net/manual/en/function.time.php. The comparison might be having a hard time comparing a full date string?
I've always found it a lot easier to use time() as its basically comparing two numbers.
$current_time = time();
$expiry_possibles_timestamp = strtotime($expiry_possibles[6]);
if ($current_time > $expiry_possibles_timestamp)
{
// Older than current time
}
I've modified your code below, try that out. Bear in mind you will need PHP 5.3 and above.
function cronexec_expired($timenow)
{
include('../../config.php');
// Open up a new MySQLi connection to the MySQL database
mysql_connect($dbHost, $dbUsername, $dbPassword);
mysql_select_db($dbTable);
// Query to check the status of the code input
$expiry_check = "SELECT * FROM code_log WHERE status='Unused'";
// Run the query
$expiry_checkexec = mysql_query($expiry_check);
while ($expiry_possibles = mysql_fetch_array($expiry_checkexec))
{
echo $expiry_possibles[6] . '<br /><br />';
echo $timenow . '<br /><br />';
$datetime = DateTime::createFromFormat('l jS \of F Y h:i:s', $expiry_possibles[6]);
if (!$datetime) continue; // Skip this execution as we cannot parse the date, so we will not trust it.
if (time() > $datetime->getTimestamp())
{
echo "Database row is in the past";
} else
{
echo "Database row is in the future";
}
}
}
That should work, although I have not tested it. How is the date stored in the database? It should be in MySQL format (YYYY-MM-DD HH:MM:SS) or in a unix timestamp format.
I recommend using the DateTime and DateInterval classes.
You can them compare if the difference is, say, exactly one day:
$expiry = new DateTime($expiry_possibles[6]);
if ($expiry->diff($time_now)->format('%d') == "1") ...
Or vice versa. There is also a procedural interface for this in the form of date_diff()
More info:
http://www.php.net/manual/en/datetime.diff.php
I'm writing a php script that iterates over the Monday of each week.
However the script seemed to get out of sync after 22nd of October.
<?php
$october_8th = strtotime("2012-10-08");
$one_week = 7 * 24 * 60 * 60;
$october_15th = $october_8th + $one_week;
$october_22nd = $october_15th + $one_week;
$october_29th = $october_22nd + $one_week;
$november_5th = $october_29th + $one_week;
echo date("Y-m-d -> l", $october_8th) . '<br />';
echo date("Y-m-d -> l", $october_15th) . '<br />';
echo date("Y-m-d -> l", $october_22nd) . '<br />';
echo date("Y-m-d -> l", $october_29th) . '<br />';
echo date("Y-m-d -> l", $november_5th) . '<br />';
This would output:
2012-10-08 -> Monday
2012-10-15 -> Monday
2012-10-22 -> Monday
2012-10-28 -> Sunday
2012-11-04 -> Sunday
I would expect it to say the 29th of October but it gets stuck at the 28th.
How should I get around this problem?
A preferred choice would be to use PHP's date-related classes to get the dates.
These classes importantly handle the daylight-savings boundaries for you, in a way that manually adding a given number of seconds to a Unix timestamp (the number from strtotime() that you used) cannot.
The following example takes your start dates and loops four times, each time adding a week to the date.
$start_date = new DateTime('2012-10-08');
$interval = new DateInterval('P1W');
$recurrences = 4;
foreach (new DatePeriod($start_date, $interval, $recurrences) as $date) {
echo $date->format('Y-m-d -> l') . '<br/>';
}
PHP Manual links:
The DatePeriod class
The DateInterval class
The DateTime class
While writing this question I discovered that day light saving time ends at the 28th of October.
Because the date at initialization doesn't contain a specific time automatically midnight is assigned. This however yields a problem when summertime ends. Suddenly the time isn't midnight anymore but one hour before that AND thus a day earlier then you would expect.
An easy fix would be to initialize the time to be midday instead of midnight:
$october_8th = strtotime("2012-10-08 12:00");
Perhaps there might be more elegant solution (you're welcome to leave one), but this will do for this purpose.
I have the following PHP code on my local apache2 webserver on a Mac Book Pro using PHP 5.3.8 and Default timezone set to Europe/Zurich:
$now = time();
$in5min = $now + 300;
echo "now: " . date('H:m:s', $now);
echo "<br>in 5 min: " . date('H:m:s', $in5min);
echo "<br>now using date only: " . date('H:m:s');
Result looks like this (run at 18:16:12, 26 July 2012):
now: 18:07:01
in 5 min: 18:07:01
now using date only: 18:07:01
Note that I can refresh the page - the seconds change, the hours and minutes remain. So 5 minutes later it's still 18:07.
What's wrong with my webserver settings? And why does the time calculation not work?
The correct format string is i for minutes, not m. m is for months.
date('H:i:s');
You're using the wrong interval, but I would suggest using DateTime::add instead:
<?php
$date = date_create('2000-01-01');
date_add($date, date_interval_create_from_date_string('10 days'));
echo date_format($date, 'Y-m-d');
?>
Haha could hit me in the face: date('H:m:s') is totally wrong. "m" is for month, not minutes. Use date('H:i:s') instead
What's the easiest way to get the UTC offset in PHP, relative to the current (system) timezone?
date('Z');
returns the UTC offset in seconds.
// will output something like +02:00 or -04:00
echo date('P');
timezone_offset_get()
$this_tz_str = date_default_timezone_get();
$this_tz = new DateTimeZone($this_tz_str);
$now = new DateTime("now", $this_tz);
$offset = $this_tz->getOffset($now);
Untested, but should work
I did a slightly modified version of what Oscar did.
date_default_timezone_set('America/New_York');
$utc_offset = date('Z') / 3600;
This gave me the offset from my timezone, EST, to UTC, in hours.
The value of $utc_offset was -4.
Simply you can do this:
//Object oriented style
function getUTCOffset_OOP($timezone)
{
$current = timezone_open($timezone);
$utcTime = new \DateTime('now', new \DateTimeZone('UTC'));
$offsetInSecs = $current->getOffset($utcTime);
$hoursAndSec = gmdate('H:i', abs($offsetInSecs));
return stripos($offsetInSecs, '-') === false ? "+{$hoursAndSec}" : "-{$hoursAndSec}";
}
//Procedural style
function getUTCOffset($timezone)
{
$current = timezone_open($timezone);
$utcTime = new \DateTime('now', new \DateTimeZone('UTC'));
$offsetInSecs = timezone_offset_get( $current, $utcTime);
$hoursAndSec = gmdate('H:i', abs($offsetInSecs));
return stripos($offsetInSecs, '-') === false ? "+{$hoursAndSec}" : "-{$hoursAndSec}";
}
$timezone = 'America/Mexico_City';
echo "Procedural style<br>";
echo getUTCOffset($timezone); //-06:00
echo "<br>";
echo "(UTC " . getUTCOffset($timezone) . ") " . $timezone; // (UTC -06:00) America/Mexico_City
echo "<br>--------------<br>";
echo "Object oriented style<br>";
echo getUTCOffset_OOP($timezone); //-06:00
echo "<br>";
echo "(UTC " . getUTCOffset_OOP($timezone) . ") " . $timezone; // (UTC -06:00) America/Mexico_City
This is same JavaScript date.getTimezoneOffset() function:
<?php
echo date('Z')/-60;
?>
This will output something formatted as: +0200 or -0400:
echo date('O');
This may be useful for a proper RSS RFC822 format
<pubDate>Sat, 07 Sep 2002 00:00:01 -0500</pubDate>
GMT offsets (like this) shouldn't use a colon (+02:00 from date('P');).
And, although it is acceptable for RSS RFC833, we don't want output like PDT and CST because these are arbitraty and "CST" can mean many things:
CST = Central Standard Time
CST = China Standard Time
CST = Cuba Standard Time
date("Z") will return the UTC offset relative to the server timezone not the user's machine timezone. To get the user's machine timezone you could use the javascript getTimezoneOffset() function which returns the time difference between UTC time and local time, in minutes.
<script type="text/javascript">
d = new Date();
window.location.href = "page.php?offset=" + d.getTimezoneOffset();
</script>
And in page.php which holds your php code, you can do whatever you want with that offset value. Or instead of redirecting to another page, you can send the offset value to your php script through Ajax, according to your needs.