UTC Offset in PHP - php

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.

Related

how to resolve time data comparism in php

I have a contract time format like this one July 28, 2020 14:18:25 that I want check if it has expired from now. But am not getting is correct. it seems to be some minutes difference
here is the code
//$now = strtotime(date("m-d-y H:i:s"));
$now = time();
$contractDate = strtotime("July 28, 2020 14:18:25");
// check if contract is still on or has ended from now
if($now < $contractDate) {
echo "contract is on";
} else {
echo "contract time ended!";
}
Could it be the timezone problem (that your time() is off by some).
You solve it by setting the timezone explicitly in your PHP scripts. You can do this with date_default_timezone_set():
date_default_timezone_set('America/Los_Angeles');
Here is the list of PHP supported timezones.
You may also want to try a test script calling date_default_timezone_get() to see what it's actually set to to verify that this is in fact the problem.
You can also try with DateTime class
$d1 = new DateTime();
$d2 = new DateTime("July 28, 2020 14:18:25");
$diff = $d1->diff($d2);
echo $diff->format('%H:%I:%S');
You are not able to get it right because of your format. It should work if you can get your dates to be in the "yyyy-mm-dd" format. Try this:
$now = strtotime(date("y-m-d"));
$now = time();
$contractDate = strtotime("2020-07-28");
if($now < $contractDate) {
echo "contract is on";
} else {
echo "contract time ended!";
}

php timezone not matching with current time on server

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

how to convert timestamp to date in codeigniter

I want to convert 1373892900000 to Monday 2013/07/15 8:55 AM in Codeigniter.
However, I keep receiving a totally different result by converting the timestamp using the function i have written, please note:I need to change the dates according to different timezones, that is why I want to write it this way:
public function time_convert($timestamp){
$this->load->helper('date');
date_default_timezone_set('UTC');
$daylight_saving = TRUE;
$timezone = "UM4"; //toronto or new york timezone
$time = gmt_to_local($timestamp, $timezone, $daylight_saving);
$final_time = standard_date('DATE_RFC822', $time);
return $final_time;
}
Result from the above function is: Sat, 08 Dec 06 01:40:00 +0000
And if I don't put date_default_timezone_set('UTC'); in the above function, I get this date instead Sat, 08 Dec 06 02:40:00 +0100. My codeigniter seems to default the timezone to Europe/Berlin.
Can anyone please help me correct any of the mistakes I might have made?
Why not just use PHP's date function?
public function time_convert($timestamp){
return date('l Y/m/d H:i', $timestamp);
}
For different timezones use a DateTime object:
public function time_convert($timestamp, $timezone = 'UTC'){
$datetime = new DateTime($timestamp, new DateTimeZone($timezone));
return $datetime->format('l Y/m/d H:i');
}
Think that should work. Note: I tihnk you need at least PHP version 5.20 for the TimeZone class.
<?php
$time_str=1373892900000;
echo gmdate("fill with your format", $time_str);
?>
your format = format your time in php, reading this page for details.
http://php.net/manual/en/function.date.php
http://php.net/manual/en/function.gmdate.php
Appears as though an invocation of standard_date with the DATE_ATOM format may sort you:
echo unix_to_human(time(), true, 'us'); # returns 2013-07-12 08:01:02 AM, for example
There are a whole host of other options for the format, enumerated on the linked page.
This how to covert timestamp to date very simple:
echo date('m/d/Y', 1299446702);
to convert timestamp to human readable format try this:
function unix_timestamp_to_human ($timestamp = "", $format = 'D d M Y - H:i:s')
{
if (empty($timestamp) || ! is_numeric($timestamp)) $timestamp = time();
return ($timestamp) ? date($format, $timestamp) : date($format, $timestamp);
}
$unix_time = "1251208071";
echo unix_timestamp_to_human($unix_time); //Return: Tue 25 Aug 2009 - 14:47:51
if you want to convert it to a format like this: 2008-07-17T09:24:17Z than use this method
<?php
$timestamp=1333699439;
echo gmdate("Y-m-d\TH:i:s\Z", $timestamp);
?>
for details about date:
http://php.net/manual/en/function.date.php
Your timestamp is coming from javascript on the client, I would guess, because it appears to be in milliseconds. php timestamps are in seconds. So to get the answer you want, first divide by 1000.
Showing the full year would have made the issue more obvious, as you would have seen the year as 45,506.

Display Time in PST

What is easiest way to display the current time in PST (West Coast) time using PHP?
Well, the easiest might be:
date_default_timezone_set('America/Los_Angeles');
echo date('Y-m-d');
Take a look at supported timezones to find one suitable for your needs.
Let's try a solution that uses PHP's modern date handling. This example requires PHP 5.2 or better.
// Right now it's about four minutes before 1 PM, PST.
$pst = new DateTimeZone('America/Los_Angeles');
$three_hours_ago = new DateTime('-3 hours', $pst); // first argument uses strtotime parsing
echo $three_hours_ago->format('Y-m-d H:i:s'); // "2010-06-15 09:56:36"
If you are using or have access to Carbon you could do this:
$timezone = 'America/Los_Angeles';
$now = Carbon::now()->tz($timezone)->toDateTimeString();
echo $now;
.
echo date('r');
putenv('TZ=PST');
echo date('r');
To convert a date/time between timezones:
include ("Date.php");
$d = new Date("2010-06-21 10:59:27"); // initialize object
$d->setTZByID("GMT"); // set local time zone
$d->convertTZByID("PST"); // convert to foreign time zone
echo $d->format("%A, %d %B %Y %T"); // retrieve converted date/time

How to display a date as iso 8601 format with PHP

I'm trying to display a datetime from my MySQL database as an iso 8601 formated string with PHP but it's coming out wrong.
17 Oct 2008 is coming out as: 1969-12-31T18:33:28-06:00 which is clearly not correct (the year should be 2008 not 1969)
This is the code I'm using:
<?= date("c", $post[3]) ?>
$post[3] is the datetime (CURRENT_TIMESTAMP) from my MySQL database.
Any ideas what's going wrong?
The second argument of date is a UNIX timestamp, not a database timestamp string.
You need to convert your database timestamp with strtotime.
<?= date("c", strtotime($post[3])) ?>
Using the DateTime class available in PHP version 5.2 it would be done like this:
$datetime = new DateTime('17 Oct 2008');
echo $datetime->format('c');
As of PHP 5.4 you can do this as a one-liner:
echo (new DateTime('17 Oct 2008'))->format('c');
Procedural style :
echo date_format(date_create('17 Oct 2008'), 'c');
// Output : 2008-10-17T00:00:00+02:00
Object oriented style :
$formatteddate = new DateTime('17 Oct 2008');
echo $datetime->format('c');
// Output : 2008-10-17T00:00:00+02:00
Hybrid 1 :
echo date_format(new DateTime('17 Oct 2008'), 'c');
// Output : 2008-10-17T00:00:00+02:00
Hybrid 2 :
echo date_create('17 Oct 2008')->format('c');
// Output : 2008-10-17T00:00:00+02:00
Notes :
1) You could also use 'Y-m-d\TH:i:sP' as an alternative to 'c' for your format.
2) The default time zone of your input is the time zone of your server. If you want the input to be for a different time zone, you need to set your time zone explicitly. This will also impact your output, however :
echo date_format(date_create('17 Oct 2008 +0800'), 'c');
// Output : 2008-10-17T00:00:00+08:00
3) If you want the output to be for a time zone different from that of your input, you can set your time zone explicitly :
echo date_format(date_create('17 Oct 2008')->setTimezone(new DateTimeZone('America/New_York')), 'c');
// Output : 2008-10-16T18:00:00-04:00
For pre PHP 5:
function iso8601($time=false) {
if(!$time) $time=time();
return date("Y-m-d", $time) . 'T' . date("H:i:s", $time) .'+00:00';
}
Here is the good function for pre PHP 5:
I added GMT difference at the end, it's not hardcoded.
function iso8601($time=false) {
if ($time === false) $time = time();
$date = date('Y-m-d\TH:i:sO', $time);
return (substr($date, 0, strlen($date)-2).':'.substr($date, -2));
}
The problem many times occurs with the milliseconds and final microseconds that many times are in 4 or 8 finals. To convert the DATE to ISO 8601 "date(DATE_ISO8601)" these are one of the solutions that works for me:
// In this form it leaves the date as it is without taking the current date as a reference
$dt = new DateTime();
echo $dt->format('Y-m-d\TH:i:s.').substr($dt->format('u'),0,3).'Z';
// return-> 2020-05-14T13:35:55.191Z
// In this form it takes the reference of the current date
echo date('Y-m-d\TH:i:s'.substr((string)microtime(), 1, 4).'\Z');
return-> 2020-05-14T13:35:55.191Z
// Various examples:
$date_in = '2020-05-25 22:12 03.056';
$dt = new DateTime($date_in);
echo $dt->format('Y-m-d\TH:i:s.').substr($dt->format('u'),0,3).'Z';
// return-> 2020-05-25T22:12:03.056Z
//In this form it takes the reference of the current date
echo date('Y-m-d\TH:i:s'.substr((string)microtime(), 1, 4).'\Z',strtotime($date_in));
// return-> 2020-05-25T14:22:05.188Z

Categories