PHP find local time by Time Zone - php

Example, I have time zone is : "Europe/London" or "America/Los_Angeles"
In Perl, I can look up for Local Time by:
use DateTime;
use DateTime::TimeZone;
$timeZoneName = "MY TIME ZONE HERE";
$timeZone = DateTime::TimeZone->new(name => $timeZoneName);
$timeNow = time();
$dateTime = DateTime->from_epoch(epoch => $timeNow);
$offset = $timeZone->offset_for_datetime($dateTime);
$localTime = $timeNow + $offset;
print "$localTime";
But I don't know how to look up local time with PHP, anyone help?

You can do this in PHP:
$timezone = 'Europe/London'; //perl: $timeZoneName = "MY TIME ZONE HERE";
$date = new DateTime('now', new DateTimeZone($timezone));
$localtime = $date->format('h:i:s a');
echo "Local time is $localtime.";
If you don't have PHP 5.2, see also date_default_timezone_set() or use ini_set('date.timezone', $timezone); and then PHP will operate as if it were in that timezone. Any date you output will be in that of the given timezone.
PHP Date/Time Functions also have good references. There are other ways you could do this in PHP but the above is simple and most servers should have PHP 5.2 or greater.
See date() for a list of formats you can pass to DateTime::format and also the DateTime Class for references on other things you can do with DateTime.

Related

How to convert UTC timestamp Value to local date time

I have a UTC timestamp value 1615958170523 and I want to convert it into our local timezone.
I have tried this method:
The timestamp is in milliseconds that's why firstly I have converted in seconds and then used the below method.
$Date = date('m-d-Y H:i:s', 1615958170523/1000);
It always returns the time ~6hours ago i.e 03-17-2021 05:16:10 (Considering current time here), I don't want to add +5:30 hours to do the same.
Is it possible that we can use a standard method that means in-built functions which may be provided by Cakephp or PHP so that I can get the answer for the same?
I have also tried this one:
$gmtTimezone = new \DateTimeZone('GMT');
$myDateTime = new \DateTime(1615958170523/1000, $gmtTimezone);
It returns the same as I have used the date function.
You need to change the timezone after to define the timestamp in GMT.
$timestamp = 1615958170523/1000;
$myDateTime = \DateTime::createFromFormat('U', (int)$timestamp);
echo $myDateTime->format('Y-m-d H:i:s'), PHP_EOL; // 2021-03-17 05:16:10
$myDateTime->setTimezone(new \DateTimeZone('Europe/Paris'));
echo $myDateTime->format('Y-m-d H:i:s'), PHP_EOL; // 2021-03-17 06:16:10
$myDateTime->setTimezone(new \DateTimeZone('America/Denver'));
echo $myDateTime->format('Y-m-d H:i:s'), PHP_EOL; // 2021-03-16 23:16:10
See DateTime::setTimezone() documentation
You should use the FrozenTime which will use the default Timezone you set in your config/app.php

Time is converted wrongly on server

Time is not converted propely on server ,
I'm converting timestamp , on local host it works well, but on server it's earlier two hours ,
$ToConvert = 1570080669;
$dt = new DateTime();
$dt->setTimestamp($ToConvert);
$EndTime = $dt->format('m/d/Y H:i');
echo $EndTime;
on local host :
10/03/2019 07:31
on Server :
10/03/2019 05:31
what might be the problem?
The DateTime class in PHP has a method called "setTimezone" which expects an instance of DatetimeZone as an argument. Using your code as an example, you just need to add one extra line as follows:
$ToConvert = 1570080669;
$dt = new DateTime();
$dt->setTimestamp($ToConvert);
$dt->setTimezone(new DatetimeZone('Europe/London'));
$EndTime = $dt->format('m/d/Y H:i');
echo $EndTime;
You can change the argument when instantiating a new timezone as desired to suit your needs.
More information is on the php.net website:
https://www.php.net/manual/en/datetime.settimezone.php

php - Parse.com change createdAt Column timezone

I'm developing a PHP project and I'm using Parse SDK. What i want to do is adjust the time given by the Parse Database. It gives me time and date that 8 hours late to my timezone. Here's the code I'm using :
$query = new ParseQuery("TestObject");
$query->get("xWMyZ4YEGZ");
$dateTime = $query->getCreatedAt();
$sched = $dateTime->format("M d, Y - hA");
echo $sched;
How can i adjust it to specifically "GMT+8" TimeZone? Thanks!
You have to set the date_default_timezone_set before doing any thing as:
if(function_exists('date_default_timezone_set'))
date_default_timezone_set($timezone);
List of timezones are provided here...
Have a look at PHP date with TZ - See N.B.'s answer here is a code snippet he suggests (you may be able to use the parse date instead of the "now" parameter):
<?php
$tz = 'Europe/London';
$timestamp = time();
$dt = new DateTime("now", new DateTimeZone($tz)); //first argument "must" be a string
$dt->setTimestamp($timestamp); //adjust the object to correct timestamp
echo $dt->format('d.m.Y, H:i:s');

Creating timestamp for 5/13/2014 # 3pm

I have an application that needs to send a UTC timestamp in order for it to work correctly. In my application a user can have any number of timezones. So if they pick 3pm and their timezone is America/New_York, it is a different 3pm than if it was America/Chicago.
I need to figure out a way to change the date into the right UTC timestamp. I know I can use date_default_timezone_set("UTC")...but I don't think will work correctly.
I think I need to calculate a difference between UTC and regular timezone, but I am not sure. Any advice is welcomes.
date_default_timezone_set("UTC");
echo strtotime('5/13/2014 3:00 PM');
1399993200
date_default_timezone_set("America/New_York");
echo strtotime('5/13/2014 3:00 PM');
1400007600
As you can tell these 2 values are different.
EDIT: Here is what my code looks like. It doesn't seem to work correctly as the application doesn't show the event in the right time.
$previous_timezone = date_default_timezone_get();
date_default_timezone_set("UTC");
$aceroute_schedule = $this->sale_lib->get_send_to_aceroute_schedule();
if (($start_time = strtotime($aceroute_schedule['aceroute_schedule_date']. ' '.$aceroute_schedule['aceroute_schedule_time_start'])) !== FALSE)
{
//Append 000 as as string for 32 bit systems
$start_epoch = $start_time.'000';
$end_epoch = strtotime('+ '.$aceroute_schedule['aceroute_duration'].' minutes', $start_time).'000';
}
else //Default to current time + 1 hour
{
//Append 000 as as string for 32 bit systems
$start_epoch = time().'000';
$end_epoch = strtotime('+1 hour', time()).'000';
}
$event->start_epoch = $start_epoch;
$event->end_epoch = $end_epoch;
Update:
This will now create a DateTime object in the user's DateTimeZone ('America/New_York'). And then it will set that object's timezone to UTC. To get the timestamp (or other string representations of date), use ::format().
# Create NY date
$NY = new DateTimeZone("America/New_York");
$NYdate = new DateTime('5/13/2014 3:00 PM', $NY);
# Set timezone to UTC
$UTC = new DateTimeZone("UTC");
$UTCdate = $NYdate->setTimezone($UTC);
# Get timestamp (PHP 5.2 compatible)
$timezone = $UTCdate->format('U');
var_dump($timezone); // a string containing UNIX timestamp
First I create 2 DateTime objects based off of their respective DateTimeZone objects. Then we can either use OOP ::diff() to get another object containing information about the time difference. Or we can use simple integers representing the difference in seconds from ::getTimestamp.
$date = '5/13/2014 3:00 PM';
# Create NY date
$NY = new DateTimeZone("America/New_York");
$NYdate = new DateTime($date, $NY);
# Create UTC date
$UTC = new DateTimeZone("UTC");
$UTCdate = new DateTime($date, $UTC);
# Find difference object
$diff = $NYdate->diff($UTCdate);
var_dump($diff); // a DateInterval object containing time difference info
# Find difference in seconds
$diff = $NYdate->getTimestamp() - $UTCdate->getTimestamp();
var_dump($diff); // an integer containing time difference in seconds
Links:
DateTimeZone
DateTime
DateInterval
Example in http://www.php.net/manual/en/datetime.settimezone.php
$date = new DateTime('2000-01-01', new DateTimeZone('Pacific/Nauru'));
echo $date->format('Y-m-d H:i:sP') . "\n";
$date->setTimezone(new DateTimeZone('Pacific/Chatham'));
echo $date->format('Y-m-d H:i:sP') . "\n";
The first line creates a DateTIme object, using the timezone Pacific/Nauru.
You can then change the timezone using setTimezone as shown in line 4, and the output will be modified accordingly.
note: the default timezone (if you don't specify it in the 2nd parameter in line 1) is the one set in your php.ini file, which you can modify (at runtime) with date_default_timezone_set("America/New_York")
note2: the 1st parameter in line 1, is equivalent to the 1st parameter of the strtotime function.
note3: the format method takes the same format parameter as date (http://www.php.net/manual/en/function.date.php)

php check if specified time has expired

I am trying to compare the current datetime, with a datetime from the database using string, as the following:
$today = new DateTime("now");
$todayString = $today->format('Y-m-d H:i:s');
if($todayString >= $rows["PrioritizationDueDate"])
{...}
$todayString keeps giving me the time 7 hours earlier (i.e now its 11:03pm, its giving me 16:04).
More, is it better to compare this way, or should i compare using datetime objects?
$todayString keeps giving me the time 7 hours earlier
you have to setup a timezone for the DateTime object I believe.
is it better to compare this way
I doubt so.
The general way is to compare in the query, using SQL to do all date calculations and return only matching rows.
Set a correct timezone in the constructor to DateTime.
$today = new DateTime("now", new DateTimeZone('TimezoneString'));
Where TimezoneString is a valid timezone string.
Edit: For a more complete example using DateTime objects, I would use DateTime::diff in conjunction with DateTime::createFromFormat.
$rows["PrioritizationDueDate"] = '2011-11-20 10:30:00';
$today = new DateTime("now", new DateTimeZone('America/New_York'));
$row_date = DateTime::createFromFormat( 'Y-m-d H:i:s', $rows["PrioritizationDueDate"], new DateTimeZone('America/New_York'));
if( $row_date->diff( $today)->format('%a') > 1)
{
echo 'The row timestamp is more than one day in the past from now.';
}
Demo
First set time zone using this function
date_default_timezone_set('UTC');
Then either you can use function strtotime() or get difference directly...

Categories