PHP How to adjust availability timezones - php

When a user signs up for my site they enter their weekly availability in this format:
Monday 1300 to 1400
Monday 2100 to 2200
Tuesday 1200 to 1300
Tuesday 1400 to 1500
Etc.
They also indicate their timezone based on a select menu, such as America/Los_Angeles.
What I want to happen is for those times to be adjusted based on the timezones of users that visit their profiles who have different timezones set. What is the best solution for this?

Store their availability as seconds from the EPOCH, and then convert those to proper times for users based on their time zone.

Store the difference between UTC and selected timezone in value of field
<option value="3">UTC+3 timezone</option>
<option value="-5">UTC-5 timezone</option>
then add or cut it from to the output of hours.
If such difference provide negative result or more than 24 hours - set next or previous day of the week.
I think you don't realy need unixtime for such intervals.

I actually ended up doing this:
<?php while ($ava = mysql_fetch_array($avail_action)) {
date_default_timezone_set($profile_owners_timezone);
$timestamp_from = strtotime($ava['time_from']);
$timestamp_to = strtotime($ava['time_to']);
date_default_timezone_set($_SESSION['timezone']);
$time_from = date("g:i A", $timestamp_from);
$time_to = date("g:i A", $timestamp_to); ?>
Basically I got the profile "owner's" timezone that he/she entered, set timezone to that, then set the timezone to "viewer's" timezone and set the variable to that.
Thanks all for the help!

Related

PHP - Display data in different time zones

Hello stackoverflow community.
I develop a web app and the concept is to display historical currency exchange rates based on time series from past.
For example a user may request exchange rates from 22 May 2020 13:00 to 26 MAY 2020 22:00. Then my backend run a loop and get the rates between those two date times each hour.
All rates in database stored in GMT time zone.
And here is the problem. Let's suppose a user make a request from a time zone offset +10:00. So if this user pick as last date time 26 MAY 2020 22:00, I guess I should grab from my database the rate in 26 MAY 2020 12:00, so to subtract 10 hours.
May this sound stupid, but I'm stuck with this.
What is my logic:
a) Get the users time zone offset via javascript in front-end
var get_timezone_offset = new Date().getTimezoneOffset();
var hrs = parseInt(-(timezone_offset / 60));
var mins = Math.abs(timezone_offset % 60);
var timezone_offset = hrs + ':' + mins;
b) Send users time zone offset to my backend
c) Get rates from my database and convert date stored from GMT to users time zone offset via PHP's Datetime object
$date = new \DateTime('2020-05-26 22:00');
$date->modify(-10 hours);
$date->format('Y-m-d H:i:s');
Is this right? I won't display wrong rates to my users.
Thank you in advance
Please read the timezone tag wiki, especially the section titled "Time Zone != Offset". In short, you cannot assume the offset taken now from the user is the same one that will apply at any other point in time.
A simple example is for time zones like America/New_York, which presently is UTC-4, but will switch to UTC-5 when daylight saving time ends in November. But besides DST, many time zones have had changes in their standard time offsets.
Instead of getting the current numeric offset, get the IANA time zone identifier from the browser.
const tzid = Intl.DateTimeFormat().resolvedOptions().timeZone;
// example: "America/New_York", "Asia/Kolkata", "Europe/Athens", etc.
Then you can use this identifier with PHP's built-in time zone support. For example, the following converts from a local time in a given time zone to the equivalent time in UTC:
$tz = new DateTimeZone("America/New_York");
$date = new DateTime('2020-05-26 22:00', $tz);
$date->setTimeZone(new DateTimeZone("UTC"));
echo $date->format('Y-m-d H:i:s');

PHP date time conversion issues related to daylight savings

I have some localisation functions within my webapp (exposed via Ajax) which enable users to display some datetime information in their own timezone as well as the timezone relating to the location of the entity the data primarily relates to.
As a result of some testing, I've discovered that whilst my code is capable of converting DB sourced date/time values accurately (i.e. including DST adjustments), the code would not calculate the correct offsets when I was using dates provided within a form. The best I've been able to achieve is converting the form date/time value to UTC but the incorrect offset is applied. This means that I need to check whether the date falls within the daylight savings range and if so, pull the datetime value back by an hour. This seems like an ugly fix and I'd appreciate it if anyone knows where I've gone wrong:
Example:
Input value of 25/11/2018 16:00 NZDT (Pacific/Auckland) = UTC+13
Output value should be 25/11/2018 14:00 ADT (Australia/Sydney) = UTC+11
If I extract the source value from the Database and then convert then the calculations work fine, no issues
If I use a form provided value (which I need to check for in case the user has updated the value without saving it), then the following occurs:
FROM DB1 = 2018-11-25 03:00:00 (value in the DB, in UTC)
FROM FORM1 = 25/11/2018 16:00 (raw value from the form)
FROM FORM2 = 2018-11-25 04:00:00 (changes to UTC-12, i.e. NZST) which is wrong, should be the same value as DB1, i.e. UTC-13 which is the offset from NZDT back to UTC)
FROM FORM3 = 2018-11-25 03:00:00 (corrected, once I check whether date/time value falls within a daylight savings range)
Code follows:
echo "FROM DB1: ".$getListing['lo_deadline']."<BR />";
echo "FROM FORM1:".$in_lo_deadline."<BR />";
$frmDateTime = DateTime::createFromFormat($this->view->user->user_datetimeformat, $in_lo_deadline,new DateTimeZone($list_tmzn));
echo "FROM FORM2:".$frmDateTime->format('Y-m-d h:i:s')."<BR />";
//If $frmDateTime is in daylight savings then subtract an hour to arrive at the correct UTC value
if ($frmDateTime->format('I'))
{
date_sub($frmDateTime, date_interval_create_from_date_string('1 hours'));
}
echo "FROM FORM3:".$frmDateTime->format('Y-m-d h:i:s')."<BR />";
$dates['set_dead'] = convertUserDate($frmDateTime->format('Y-m-d h:i:s'), $this->view->user->user_datetimeformat, $user_tmzn,'UTC');
What I understand from your code, the reason why it's showing 2018-11-25 04:00:00 is because of AM/PM format. You should be using capital H instead of h in your code.
You need to understand the difference between 24 hour and 12 hour formats. 2018-11-25 04:00:00 according to your format is in AM/PM or 12 hour format, but in 24 hour format it should be 2018-11-25 16:00:00. Database time is always in 24 hour format.
Change
$frmDateTime->format('Y-m-d h:i:s')
to
$frmDateTime->format('Y-m-d H:i:s')
Note: You don't need to manually subtract an hour to calculate daylight saving time as php does it automatically.

How to calculate average time of day taking into account timezone differences?

I'm using Laravel/PHP/MySQL and storing all dates and times in UTC.
The user can select a timezone (for example Eastern), enter a date and time, and the date and time will be converted to UTC before storing. On retrieval it will be converted to user's selected timezone.
My question is how can you get the average time of day from a series of records taking into account the timezone (preferably in the database query)? The following question addresses average time of day in PHP, but not the timezone issue.
How to calculate average time
Here is what I'm doing:
SEC_TO_TIME( AVG( TIME_TO_SEC( TIME(flights.departed_at) ) ) ) ) AS average_time
This works except for records that span daylight saving/standard time in a region that observes it.
FOR EXAMPLE: You may have a record with the UTC datetime of 2015-08-18 11:00:00 that was entered by a user in EDT at 2015-08-18 07:00:00. Then you have a second record entered with the UTC datetime of 2015-11-10 12:00:00 by a user in EST at 2015-11-10 07:00:00. If you try to calculate the average time of day it should equate to 07:00:00 but instead the result is 07:30:00.
Any ideas how to overcome this? Am I approaching this all wrong?
Thanks in advance.
In short, your code is working correctly. Once the date is in UTC, you'd have to re-calculate whether or not it was entered (1) during daylight savings time, (2) by someone actually observing daylight savings time, and (3) in a place that recognizes daylight savings time.
I can really only think of one way to approach this.
Add some kind of flag when the data is saved to mark the timestamp as DST. You can use this flag to adjust for the hour difference. How you generate this flag is up to you.
If you have all your times stored in Z, and if your MySQL database has the timezones loaded correctly, you can use the zoneinfo timezone name to retrieve your local times. For example,
SELECT CONVERT_TZ('2015-08-01 11:00', 'UTC', 'America/New_York'),
CONVERT_TZ('2015-12-01 12:00', 'UTC', 'America/New_York')
yields
2015-08-01 07:00 2015-12-01 07:00
The point is, the zoneinfo database knows to use daylight saving time or standard time for each datetime value. It doesn't use the current offset, it uses the offset in effect on the date in question.
So, you can retrieve the time of day, in local time, with an expression like this:
TIME(CONVERT_TZ(utc_time_column, 'UTC', 'America/New_York'))
Then, you average those times-of-day in the usual way.

Adding timezone and minutes to a date/time received from multiple parameters

I'm making a mail system application, in which the user selects the date and time to send the email one.
He selects the date from a jQuery datepicker, then hours from a drop down ranging from 01-24 and then minutes from a drop down ranging from 01-60.
Finally, I make a date with this setting :-
$time = $_POST['hours'] . ":" . $_POST['minutes'];
and date my
$_POST['datepicker']
But here is the deal, I need to add the timezone to the hours as well, and the date should be settled accordingly to the time we get after adding the timezone. Suppose we select 23:50 and add +3:30 then the date will be changed as well.
I tried to do it with simple calculations, but results were stupid.
I also need to add 5 minutes to the minutes, so suppose the input is 23:56 and time zone +3:30, then 56+5 = 01 (next day) and then the timezone is added as well.
I have timezone likes this
<select name="timezone">
<option value="1:30">1:30</option>
<option value="-5:30">-5:30</option>
What would be the best way to get the required time with the correct date?
Any suggestion is helpful.

How do you rotate text strings contingent on the time of day, in PHP?

I am trying to rotate phone numbers depending on the time of day. If the time is between 8am and 5pm, it should show the 888 number. If it is after 5pm but before 8am it should show the 777 number. This is what I got thus far, but it only shows the 777 number as my output, even though the time is between the hours of 8am and 5pm.
$dayPhoneNumber = "1-888-888-8888";
$nightPhoneNumber = "1-777-777-7777";
$currentPhoneNumber = "";
$nowHour = date("H");
$startHour = 8;
$endHour = 17;
if ($nowHour >= $startHour && $nowHour <= $endHour){
echo $dayPhoneNumber;
} else {
echo $nightPhoneNumber;
}
My guess is your server's time is not the same as your computer's time. If you're using a hosting solution, your server may very well be across the country or on a different continent, meaning the time will be different.
If you just need to worry about one location and not where the end user is, then this should be easy to do. If you're on the West Coast of the US
date_default_timezone_set("America/Los_Angeles");
$hour = date("H", time());
Here is a list of Time Zones: http://www.php.net/manual/en/timezones.php
If you need to know the end user's time zone when determining the hour, here's a discussion on doing that: How to get client's timezone?
If you're dealing with time zone issues, you may also want to retrieve the time using UTC, and then add or subtract whatever number of hours to get to the correct time zone: get UTC time in PHP

Categories