php


PHP DateTime operations - set new timezone and deduct 24 hours


I am having a surprisingly hard time with the datetime() statement in PHP. What I am trying to achieve is to read the current server time (located in GMT-5), based on that time calculate the user specific date and time as per timezone, and then deduct 24 hours from the users current time. See an example below for users in London and Shanghai:
$timezone = date_default_timezone_get();
echo "The current server timezone is: " . $timezone;
echo "<hr>";
$server_datetime = new \DateTime('now'); //located in America/New_York timezone - GMT-5
$server_newdate = (new \DateTime())->modify('-1 day');
echo "Current Server DateTime: " . $server_datetime->format('Y-m-d H:i:s') . "<br>";
echo "If you deduct 24 hours you get " . $server_newdate->format('Y-m-d H:i:s');
echo "<hr>";
$usersTimezone1 = 'Europe/London'; // GMT-0
$user_datetime1 = $server_datetime->setTimezone(new DateTimeZone($usersTimezone1));
$user_newdate1 = ($server_datetime->setTimezone(new DateTimeZone($usersTimezone1))->modify('-1 day'));
//$user_newdate1 = $user_datetime1->modify('-1 day');
echo "London User DateTime: " . $user_datetime1->format('Y-m-d H:i:s') . "<br>";
echo "If you deduct 24 hours you get " . $user_newdate1->format('Y-m-d H:i:s');
echo "<hr>";
$usersTimezone2 = 'Asia/Shanghai'; // GMT+8
$user_datetime2 = $server_datetime->setTimezone(new DateTimeZone($usersTimezone2));
$user_newdate2 = $user_datetime1->modify('-1 day');
echo "Shanghai User DateTime: " . $user_datetime2->format('Y-m-d H:i:s') . "<br>";
echo "If you deduct 24 hours you get " . $user_newdate2->format('Y-m-d H:i:s');
As you can see, the problem is that I cannot deduct the 24 hours directly from the $user_datetime variable which holds the current time of the user's timezone. Neither deducting from the variable directly nor creating a new instance of datetime() for this timezone seems to do the trick.
// attempt 1 - not working
$user_datetime1 = $server_datetime->setTimezone(new DateTimeZone($usersTimezone1));
$user_newdate1 = ($server_datetime->setTimezone(new DateTimeZone($usersTimezone1))->modify('-1 day'));
// attempt 2 - not working either
$user_datetime2 = $server_datetime->setTimezone(new DateTimeZone($usersTimezone2));
$user_newdate2 = $user_datetime1->modify('-1 day');
As soon as I start modifying the users datetime, the script will only return the current date and time of the users timezone, nothing else.
Thanks for the help
As a sort of best practice, you can use this:
$serverDateTime = new DateTime();
$userTimezone = new DateTimeZone('Europe/London');
$userDateTime = $serverDateTime->setTimezone($userTimezone);
$dateInterval = new DateInterval('P1D');
echo $userDateTime->sub($dateInterval)->format('Y-m-d H:i:s');
But if you want to subtract directly from the variable, you can use this one:
$serverDateTime = new DateTime();
$userTimezone = new DateTimeZone('Europe/London');
$userDateTime = $serverDateTime->setTimezone($userTimezone)->sub(new DateInterval('P1D'))->format('Y-m-d H:i:s');
echo $userDateTime;
//Asia/Kolkata +5:30
date_default_timezone_set("Asia/Kolkata");//set time zone
$istTime= strtotime(date("d-m-Y h:i:s"));//get timestamp in seconds
echo date("d-m-Y h:i:s");//16-03-2017 09:44:52
//Europe/London +0:00
date_default_timezone_set("Europe/London");//set new time zone
$dayBeforeTime= strtotime(date("d-m-Y h:i:s",$istTime))-86400;//get timestamp in seconds and subtracting 1 day seconds
echo date("d-m-Y h:i:s",$dayBeforeTime);//15-03-2017 04:14:52

Related Links

Strange error log results for php pages
PHP Laravel order parent by child
DOMPDF generated pdf result getting messed up
Laravel 5.3 - Internal redirect or modify request middleware
passport oauth/authorize always redirect login fixed, but Client authentication failed
How do I create an image, preferably .png, from an array containing blob data split into 4 elements?
Fitbit API unable to fetch data synced through Fitbit device i.e Blaze
User provider error symfony
Connection failed to MSSQL in php
Access denied to database with phpunit in Laravel
Symfony how to valid a form after login
minimum file size for correctly work exif_imagetype
Problems converting an object into JSON in php
Laravel get conversation where users in array
Multidimensional array get value from parent array
How to count most popular (recurring) attribute through Many-To-Many relationship in Laravel 5.3?

Categories

HOME
xpath
mc
azure-functions
subdomain
ews
firebase-database
phpmqtt
joomla3.2
graphql-js
kurento
mailing-list
xamarin-zebble
cqrs
locationmanager
amazon-emr
ex
spring-jpa
squirrel-sql
distributed-computing
salt-cloud
pfobject
spyder
angular2-highcharts
data-type-conversion
device
react-dnd
crud
basex
code-climate
django-import-export
materialize
d3.js-v4
dotcms
phpstorm-2016.1
mapnik
rust-cargo
actframework
cucumber-junit
ms-media-foundation
nest
dreamfactory
redgate
unification
plane
viewcontroller
httphandler
web-inspector
type-inference
react-intl
liteide
sonarqube5.2
md5-file
amazon-elastic-beanstalk
android-sharing
line-intersection
sequence-diagram
mura
dex
word-2016
google-shopping-api
ipywidgets
json-spirit
python-cffi
msgpack
variable-length-array
fanotify
canopy
wso2ml
modern.ie
dynamics-ax-2012-r2
karma-coverage
scala-swing
innerhtml
mathematical-expressions
mxe
uno
ildasm
commenting
mod-perl
windows-taskbar
lsa
mp4parser
stty
libxml-js
axacropdf
mongo-jackson-mapper
ui-design
semicolon
itunes-sdk
getopt-long
jzmq
prefuse
firebird1.5
n-queens
microblogging
mvcrecaptcha
filelock
jmenu
bll
ccl
outlook-2007-addin
principles
html-components
3270
.net-client-profile
fuzzy-comparison
rakudo
html-generation

Resources

Mobile Apps Dev
Database Users
javascript
java
csharp
php
android
MS Developer
developer works
python
ios
c
html
jquery
RDBMS discuss
Cloud Virtualization
Database Dev&Adm
javascript
java
csharp
php
python
android
jquery
ruby
ios
html
Mobile App
Mobile App
Mobile App