PHP DateTime operations - set new timezone and deduct 24 hours - php

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

I want to count "hours into a month" in php

The following code helps me project data from a database onto our internal adminsite for the current day.
Since we're in multiple time zones, we use UTC time for basic time function, but since our office is in California, we want the date to actually be = ($date)'hours' - 8, because PST is 8 hours behind.
We use the following logic to show the "previous day" if it's "a day ahead" UTC time but the same day our time, which works great, however, on the last day of the month at 4 PM, all of our data is hidden.
<?php
$date = getDate();
if ($date['hours'] < 8) {
$dateDay = $date['mday']-1;
} else {
$dateDay = $date['mday'];
}
$dateMonth = $date['mon'];
// last day of month
// $dateMonth = $date['mon'] - 1;
$dateYear = $date['year'];
$dateTime = $dateYear . "-" . $dateMonth . '-' . $dateDay . ' 08:00:00';
So, this 'if' function works great to show the true "day." What it says is, if the UTC hour < 8, then it's actually yesterday, as 3 AM UTC time is actually 7 PM the day before PST.
What I was wondering is if there's a way to track "month hours", so I could use the same 'if' function that reads "if we're less than 8 UTC hours into the month, it's actually still last month."
That way it'll work regardless of whether the month has 28, 30 , or 31 days. Does such logic exist?
I think its the best way to deal with it :
<?php
$date = new DateTime('2016-08-08', new DateTimeZone('UTC'));
echo $date->format('Y-m-d H:i:sP') . "\n";
$date->setTimezone(new DateTimeZone('America/Los_Angeles'));
echo $date->format('Y-m-d H:i:sP') . "\n";
?>
You can use DateTime::sub or DateTime::modify method which will keep correct month for you:
$now = new DateTime(getDay()); // supposing getDate() returns something that can be parsed with DateTime constructor
// Unless using DateTimeImmutable, cloning is needed to prevent altering the original object
$min = clone ($now);
$min->modify('-8 hours');
// alternatively $min->sub(new DateInterval('PT8H'));
if ($now->format('m') !== $min->format('m')) {
// month differs
}

PHP: Convert Local Time to UTC

Assume I get a string like 08/22/2015 10:56 PM and that this date/time string always refers to only one particular time zone. I need to be able to convert that to this format: 'Ymd\THis\Z', which is the iCal format.
How do I convert that string to Zulu time and into 'Ymd\THis\Z'
How do I then add, say, 30 minutes to that date/time?
Been trying to hack this with strtotime and DateTime, but I'm worried that I'm going about this the wrong way. Maybe there's a simpler and more straightforward solution?
You can use DateTime, example bellow:
<?php
$datetime = '08/22/2015 10:56 PM';
$tz_from = 'America/New_York';
$tz_to = 'UTC';
$format = 'Ymd\THis\Z';
$dt = new DateTime($datetime, new DateTimeZone($tz_from));
$dt->setTimeZone(new DateTimeZone($tz_to));
echo $dt->format($format) . "\n";
$minutes = 30;
$dt->add(new DateInterval('PT' . $minutes . 'M'));
echo $dt->format($format) . "\n";
according to subject line; To convert local time to UTC you need the timezone name of given local time, or if you have timezone offset in GMT; you can try the following:
//assume time zone is +3 hours
$offset = 3 * 60 * 60;
$date = date('H:i:s', strtotime("10:56 PM")- $offset);
echo $date;
This will output : 19:56:00 which is UTC Time

How to get difference of a time in seconds in PHP?

I have a database column with datatype "time" which stores 11:30:45. I have fetched this time in a variable say
$databasetime = 11:30:45
I want to declare a variable say $currenttime which will contain time just now. Like its 11:33:30 right now and another variable which will contain their difference in seconds like
$timediff = $currenttime - $databasetime;
echo $timediff;
I am trying $currenttime = time(); but I am not getting the result which I desire. I want $timediff = 165 but when I echo time(), I am getting a very big value.
$databasetime = strtotime('11:30:45');
$curtime = time();
echo $curtime - $databasetime;
You can do it in the following way:
$databasetime = '11:30:45';
$time1 = strtotime($databasetime);
$time2 = strtotime('now');
$diff = $time2 - $time1;
echo 'your difference: '.date('H:i:s', $diff);
$datetime1 = new DateTime('10:35:56 2013-11-17');
$datetime2 = new DateTime('10:35:50 2013-11-17');
$interval = $datetime1->diff($datetime2);
echo $interval->m . " Month " .$interval->d ." Days ". $interval->h . " Hours, " . $interval->i." Mintues, ".$interval->s." seconds <br/>";
<?php
$currentTime = time();
$futureDateTime = new DateTime('11:30:45'); // might want to specify a date and timezone, system TZ by default
$futureTime = $futureDateTime->format('U'); // get unix timestamp
$timeDiff = $futureTime-$currentTime;
?>
You use the DateTime 'OO' methods to return 'unix timestamp' integers directly
<?php
$now = new DateTime('now');
$date = new DateTime('11:30:45');
echo $now->getTimestamp() - $date->getTimestamp();
?>
Here is a simple example.
$databasetime = '11:30:45';
$timedif = abs(strtotime('now') - strtotime($databasetime));
echo $timedif; //echos the difference in seconds.
abs is used just to prevent neg numbers, which you may or may not want to do.
My problem is solved now. Actually all answers are right but the problem was due to the default time zone. I wanted Asia/Kolkata time zone but default European timezone apache was picking. That's why I was not getting my desired results.
So, I am finally using below code:
date_default_timezone_set('Asia/Kolkata');
$databasetime = strtotime('11:30:45');
$curtime = time();
echo $curtime - $databasetime;

PHP Diff Partial Datetime

I'm trying to subtract the time difference between the current datetime, and a time stated in my database. The datetimes current format is yyyy:mm:dd hh:mm:ss, however for this specific case i just want to subtract the time and not the date so i only want hh:mm:ss to be calculated and then stored into a different variable i can use and format how i want. Is it possible to take a full datetime, break it apart and do a diff on it? I think this is kind of confusing so ask if you need clarification. Here's what i've tried thus far:
<?php
//The time in the database
$classTime = DateTime::createFromFormat('Y-m-d H:i:s', '0000-00-00 18:30:00');
$timein = new DateTime("now", new DateTimeZone('America/Detroit'));
$timein->getTimestamp();
$timeout = $classTime;
$totaltime = $timeout->diff($timein);
$totaltime = $totaltime->format('Y-m-d H:i:s');
$totaltime = date('0000:00:00 H:i:s', strtotime($totaltime));
//I create a new date because i'm storing this time into the database, which can't be done with a datetime.
//FORMAT TIMES
$timein = $timein->format('Y-m-d H:i:s');
$timeout = $timeout->format('Y-m-d H:i:s');
echo "Time in " . $timein . " Time Out " . $timeout . " Total Time " . $totaltime;
?>
This current output returns:
Time in 2013-04-02 14:05:32 Time Out -0001-11-30 18:30:00 Total Time 0000:00:00 00:00:00
But i want it to return something like:
Time in 2013-04-02 14:05:32 Time Out -0000-00-00 18:30:00 Total Time 0000:00:00 03:30:00
Your question isn't very clear and I spent quite a bit of time answering the wrong question until I took a careful look at your code to see what you actually wanted.
As far as I understand it you store the finishing time of a lesson in your database as a MySql Datetime type and you want to find the time remaining between now and the time the lesson ends.
I'll ignore timezones for the purpose of this answer.
You start with
$classTime = DateTime::createFromFormat('Y-m-d H:i:s', '0000-00-00 18:30:00');
To do a meaningful time comparison, the date portion of $classTime needs to be set to today:-
$timeIn = new DateTime();
$year = (int)$timeIn->format('Y');
$month = (int)$timeIn->format('m');
$day = (int)$timeIn->format('d');
$classTime->setDate($year, $month, $day);
You can then do the comparison:-
$diff = $timeIn->diff($classTime);
$diff is now an instance of DateInterval.
We can now echo out the information:-
$start = $timeIn->format('Y-m-d H:i:s');
$end = $classTime->format('Y-m-d H:i:s');
$duration = $diff->format("%Hh, %Im, %Ss");
echo "Time in: $start, Time out: $end, Duration: $duration";
Which at the time I ran the code, gave the following output:-
Time in: 2013-04-05 13:22:54, Time out: 2013-04-05 18:30:00, Duration: 05h, 07m, 06s

Setting a time and date and adding to it in PHP

Basically am trying to set a time and a date in PHP then set a time gap which will range between minutes, loop through between a start time and end time echoing something out for each one. Have tried loads of different ways and cant seem to figure a way to set a date and add to it.
This seems the best script I have modified so far:
$minutes = 5;
$endtime = new DateTime('2012-01-01 09:00');
$newendtime = $endtime->format('Y-m-d H:i');
$timedate = new DateTime('2012-01-01 09:00');
while($stamp < $newendtime)
{
$time = new DateTime($timedate);
$time->add(new DateInterval('PT' . $minutes . 'M'));
$timedate = $time->format('Y-m-d H:i');
echo $timedate;
}
$minutes = 5;
$endtime = new DateTime('2012-01-01 09:00');
//modified the start value to get something _before_ the endtime:
$time = new DateTime('2012-01-01 8:00');
$interval = new DateInterval('PT' . $minutes . 'M');
while($time < $endtime){
$time->add($interval);
echo $time->format('Y-m-d H:i');
}
Do everything in seconds, and use php's time(), date(), and mktime functions.
In UNIX Time, dates are stored as the number of seconds since Jan 1, 1970.
You can render UNIX Timestamps with date().
$time = time(); // gets current time
$endtime = mktime(0,0,0, 1, 31, 2012); // set jan 31 # midnight as end time
$interval = 60 * 5; // 300 seconds = 5 minutes
while($time < $endtime){
$time += $interval;
echo date("M jS Y h:i:s a",$time) . "<br>"; // echos time as Jan 17th, 2012 1:04:56 pm
}
date reference:
http://us3.php.net/manual/en/function.date.php (includes superb date format reference too)
mktime reference: http://us2.php.net/mktime
time() only gets the current time, but just for kicks n' giggles: http://us2.php.net/time
And, it's super easy to store in a database!
This function will let you add date to your existing datetime. This will also preserves HH:MM:SS
<?php
function add_date($givendate,$day=0,$mth=0,$yr=0) {
$cd = strtotime($givendate);
$newdate = date('Y-m-d h:i:s', mktime(date('h',$cd),
date('i',$cd), date('s',$cd), date('m',$cd)+$mth,
date('d',$cd)+$day, date('Y',$cd)+$yr));
return $newdate;
}
?>
Usage:
add_date($date,12,0,0);
where $date is your date.

Categories