Converting a date from local timezone to UTC - php

I have a Laravel-based app that is used by people from various parts of the US.
I am capturing a timestamp in Javascript when the user takes a specific action, and then I am submitting that timestamp as form data, for the Laravel/PHP to process.
The timestamp that I am capture in Javascript is in typical "YYYY-MM-DD HH:MM:SS" format.
I have the timezone the user is in stored in a database.
I basically want to take that timestamp, and convert it to UTC time, so that all timestamps in the database are UTC.
That is where I am struggling.
I have the following PHP code:
$defaultTime = request('submitted-time-stamp'); //In this case, we'll say 2022-12-21 12:01:01
$defaultTZ = $user->time_zone; //Translates to America/Denver
$utcTime = new DateTime($defaultTime);
$convertedTime = $utcTime1->setTimeZone(new DateTimeZone('UTC'));
$formattedTime = $convertedTime->format("Y-m-d H:i:s");
echo $formattedTime;
This code – it isn't producing any errors per sé... but it is showing the wrong time. It's showing the time that it went in as, not the time converted to UTC.
Basically, if I submit "2022-12-21 12:01:01" as the time, the converted time SHOULD be "2022-12-21 19:01:01", but it's still just echoing out "2022-12-21 12:01:01".
What am I missing here?

setTimezone() changes the timezone of the object from whatever default it was created with. I.e., it means, "convert from the existing timezone to this new timezone." It does not mean, "interpret the time as if it were in this timezone." If the original string didn't contain some sort of timezone identifier, then that default is whatever your PHP config says.
$when = new DateTime('2022-12-21 12:01:01');
echo $when->getTimeZone()->getName();
This will be the same as:
echo date_default_timezone_get();
Which is probably not what you want unless all your users are in the same timezone as your server.
In order to create a DateTime object in a specific known timezone that is not the same as your server's default, you'll need one of two things -- either a timezone representation in the input string:
$when = new DateTime('2022-12-21 12:01:01 America/New_York');
Or an explicit default timezone passed as a second parameter to the DateTime constructor:
$userDefaultTzStr = 'America/New_York'; // read this value from the database
$defaultTz = new DateTimeZone($userDefaultTzStr);
$when = new DateTime('2022-12-21 12:01:01', $defaultTz);
This latter method is (probably) preferred. If the input string contains any sort of timezone identifier, that will be used and the second parameter will be ignored. But if the input string does not contain any sort of timezone identifier, then the string will be interpreted as if it were in the indicated timezone.

Using Carbon it's very trivial.
use Carbon\Carbon;
$date = Carbon::create(request('submitted-time-stamp'), $user->time_zone);
$date->tz('UTC');
echo $date->format('Y-m-d H:i:s');
It should be the same thing with Laravel's Date facade.
use Illuminate\Support\Facades\Date;
$date = Date::create(request('submitted-time-stamp'), $user->time_zone);
$date->tz('UTC');
echo $date->format('Y-m-d H:i:s');

Related

timestamp from both date & time inputs and compare php

I've been struggling to get an exact answer for this question. There are many that are close to what I'm wanting but seem to still be just off. The application of this is to ensure that a booking can't be made for a past date.
I have a form which has an input for time & another for date. Firstly, I wan't to take both of these inputs & convert them to a timestamp.
This code returns nothing
$time_date = sprintf("%s %s", $pDate, $pTime);
$objDate = DateTime::createFromFormat('H:ia d/m/Y', $time_date);
$stamp = $objDate->getTimestamp();
echo $stamp;
So I've have tried using something like this
$pDate = $_POST['pDate'];
$pTime = $_POST['pTime'];
$full_date = $pDate . ' ' . $pTime;
$timestamp = strtotime($full_date);
echo $timestamp;
But for some reason it is returning an incorrect timestamp. (i've been using an online converter) 02/06/2014 as date & 12:23am as time, is not 1401625380. This according to the converter is Sun, 01 Jun 2014 12:23:00 GMT.
Does someone have working code for returning a timestamp of both time & date inputs?
Secondly I want to compare this timestamp with a specified one & check to see if it is greater than. I've created a timestamp for my timezone with this
$date = new DateTime(null, new DateTimeZone('Pacific/Auckland'));
$cDate = $date->getTimestamp();
echo $cDate;
and will simply have an if statement which compares the two and echos the appropriate message.
I feel as though there are multiple question on here that are ALMOST what I'm wanting to achieve but I can't manage to get them working. Apologies for the near duplicate.
Note: I'm using ajax to post form data (if this could possibly interfere).
Your second code snipped is correct. Assuming it's in datetime format (Y-m-d H:i:s).
From php manual about strtotime():
Each parameter of this function uses the default time zone unless a time zone is specified in that parameter.
Check your PHP default time zone with date_default_timezone_get() function.
To compare two dates, be sure they both are in same time zones.
For datetime inputs I personally use jQuery UI timepicker addon.
you receiving the time and date in string format - so i don't believe the ajax can interfere.
as for your question:
first of all - find out what is the locale timezone of your server. you can do it by this function: date_default_timezone_get.
if the answer doesn't suit you - you can use its "sister": date_default_timezone_set, and change it to whatever value you need (like 'Pacific/Auckland' - see the documentation there). it is also recommended to return it to the original value after you finish your stuff.
i believe fixing your locale timezone will solve your issue.

Unix time stamp gives different results in PHP

I am using the following code to generate time stamps I always get different results for the same input on
$EventDateZone = new DateTime(str_replace('/', '-', $record['Date']), new DateTimeZone(Config::get('app.timezone')));
$EventDate = strtotime($EventDateZone->format("Y-m-d"));
$EventTimeZone = new DateTime($record['Time'], new DateTimeZone(Config::get('app.timezone')));
$EventTime = strtotime($EventTimeZone->format("H:i:s"));
The variables $record['Date] includes 01/04/2014 and $record['Time'] includes 09:26:00 AM and Config::get('app.timezone') is Asia/Dubai
The problem with the converted time it is always different here are the result for the converted time 1398576360 and 1398662760
I need the generated time stamp to be identical as this record will be stored in the database and I don't want to have it duplicated.
The date value does not contain a time, and the time value does not contain a date. UNIX timestamps however are compound values which are date-time values and must contain both. When you instantiate a new DateTime object and you give it an incomplete timestamp (i.e. missing either date or time), it fills in the missing values from the current time. And that will of course always be different.
You'll have to instantiate the DateTime object with both to get your UNIX timestamp. You cannot output a UNIX timestamp separately for date and time, because that doesn't make any sense. Your strtotime code doesn't make any sense. You can separate the DateTime object into date and time components again later if necessary, but not into two separate UNIX timestamps.
$event = DateTime::createFromFormat(
'd/m/Y H:i:s',
"$record[Date] $record[Time]",
new DateTimeZone(Config::get('app.timezone'))
);
echo $event->getTimestamp();
echo $event->format('Y-m-d');
echo $event->format('H:i:s');

convert to UTC without changing php timezone settings

How can I convert the time zone of a date string in php without changing the default time zone. I want to convert it locally to display only. The php time zone settting should not be modified.
EDIT:
My source time is a UTC string, I want to convert it to a different format, retaining the time zone as UTC, but php is converting it to local timezone.
The code I used was:
date('Y-m-d H:i::s',strtotime($time_str));
How do I retain timezone?
$src_tz = new DateTimeZone('America/Chicago');
$dest_tz = new DateTimeZone('America/New_York');
$dt = new DateTime("2000-01-01 12:00:00", $src_tz);
$dt->setTimeZone($dest_tz);
echo $dt->format('Y-m-d H:i:s');
Note that if the source time is UTC, you can change the one line to this:
$dt = new DateTime("2000-01-01 12:00:00 UTC");
Edit: Looks like you want to go to UTC. In that case, just use "UTC" as the parameter to the $dest_tz constructor, and use the original block of code. (And of course, you can omit the $src_tz parameter if it is the same as the default time zone.)

PHP & MySQL: Converting Stored TIMESTAMP into User's Local Timezone

So I have a site with a comments feature where the timestamp of the comment is stored in a MySQL database. From what I understand, the timestamp is converted to UTC when stored, then converted back to the default timezone when retrieved. In my case, my server is in the Central Daylight Time timezone (CDT).
I have a plan to get the timezone from each user via entry form. I just wanted to know how to convert the TIMESTAMP value into the user's timezone.
First, would I convert from UTC to local timezone? Or CDT to local timezone?
Secondly, how would I go about doing that in PHP? Would I just do:
$userTimezone = new DateTimeZone($userSubmittedTimezoneString);
$myDateTime = new DateTime($storedTimestamp, $userTimezone);
...or is that not correct?
Date/time/datetime values are stored in MySQL as you supply them. I.e. if you INSERT the string 2012-04-17 12:03:23 into a DATETIME column, that's the value that will be stored. It will be converted internally into a timestamp which may or may not be accurate (see below), but when you query for the value again, you'll get the same value back out; the roundtrip is transparent.
Problems may occur if you try to do time calculations inside SQL. I.e. any operation that requires SQL to take the timezone and/or the server time into account. For example, using NOW(). For any of those operations, the timezone and/or server time should be set correctly. See Time Zone Problems.
If that doesn't concern you and you only need to do calculations in PHP, you only need to make sure you know from which timezone to which timezone you want to convert. For that purpose it can be convenient to standardize all times to UTC, but it is not necessary, as timezone conversions from any timezone to any other timezone work just as well, as long as you're clear about which timezone you're converting from and to.
date_default_timezone_set('Asia/Tokyo'); // your reference timezone here
$date = date('Y-m-d H:i:s');
/* INSERT $date INTO database */;
$date = /* SELECT date FROM database */;
$usersTimezone = new DateTimeZone('America/Vancouver');
$l10nDate = new DateTime($date);
$l10nDate->setTimeZone($usersTimezone);
echo $l10nDate->format('Y-m-d H:i:s');
There is no reliable way to get the user's timezone. Timezone information is not sent in HTTP headers. The best that you could do is either:
Match the IP address againsta geographic database
-or-
Use Javascript to get the time set on the user's computer and either send that to the server (AJAX) or make the time string on the client.
$timezone = new DateTimeZone('America/Vancouver');
$date = new DateTime(date('m/d/Y h:i:s a', time()));
$date->setTimeZone($timezone);
echo $date->format('l F j Y g:i:s A')."\n";
Replace new DateTime(date('m/d/Y h:i:s a', time())); with new DateTime("UTC Time");
You can create a new DateTimeZone() object for each user input.
The way to do it is by using javascript. I think the best way to do it is by storing the users GMT into his cookies, and retrieving it on the PHP process form.
<script language="javascript">
function TimeZoneCookie()
{
var u_gmt = (-(new Date().getTimezoneOffset()))/60;
var o_date = new Date("December 31, 2025");
var v_cookie_date = o_date.toGMTString();
var str_cookie = "utimezone="+u_gmt;
str_cookie += ";expires=" + v_cookie_date;
document.cookie=str_cookie;
}
//---------------------
TimeZoneCookie();
</script>
u_gmt explained:
Date().getTimezoneOffset() returns the offset to GMT-0 in minutes
Since getTimezoneOffset() will return the offset to GMT-0 and not from GMT-0 we'll need to turn it around. How? simple, just by knowing that -*-=+ & -*+=-. If you know basic math, you already know this principle.
As I said in step 1 getTimezoneOffset() will return the offset in minutes, so we just divide it by 60, so we can get the gmt offset format.
Result: (-(new Date().getTimezoneOffset()))/60
Now retrieve the cookie in PHP:
<?php
$user_timezone = $_COOKIE['utimezone'];
?>

PHP timezone function not working

I'm creating a forum, which also stores the time a post was sent, and I need to convert that into the user's timezone.
Now, the MySQL DataBase stores the time with UTC_TIMESTAMP() (in a column with the DATETIME type), and I created a little function from the code on http://www.ultramegatech.com/blog/2009/04/working-with-time-zones-in-php/ to convert the time to the user's timezone. This is the function:
function convertTZ($timestamp, $tz='UTC', $format='d-m-Y H:i:s') {
// timestamp to convert
$timestamp = strtotime($timestamp);
// the time formatting to use
$format = $format;
// the time zone provided
$tz = $tz;
// create the DateTimeZone object for later
$dtzone = new DateTimeZone($tz);
// first convert the timestamp into an RFC 2822 formatted date
$time = date('r', $timestamp);
// now create the DateTime object for this time
$dtime = new DateTime($time);
// convert this to the user's timezone using the DateTimeZone object
$dtime->setTimeZone($dtzone);
// print the time using your preferred format
$time = $dtime->format($format);
return $time;
}
And I made a test page at http://assets.momo40k.ch/timezones.php.
Now, when I insert a post into the DataBase at, say, 11:50 in my timezone (which is Europe/Rome), it inserts 09:50 in UTC, wich is correct, according to some online timezone converters.
But when I try to convert it back to Europe/Rome with the convertTZ() function, it returns 09:50, as if Europe/Rome is UTC. If I try converting it to a GMT+2:00 timezone, it returns 10:50. Can anyone fugure out why this is?
P.S: I'm not using the CONVERT_TZ() SQL function because my server does not support named timezones, so this function is my workaround.
Make sure your stored timestamps are UTC:
$date = new DateTime($timestamp, new DateTimeZone("UTC"));
$date->format(DATE_W3C); // does it gives the expected result ?
BTW your function can be simplified to this:
function convertTZ($timestamp, $tz='UTC', $format='d-m-Y H:i:s') {
$dtime = new DateTime($timestamp, new DateTimeZone("UTC"))
$dtime->setTimezone(new DateTimeZone("UTC"));
return $dtime->format($format);
}
MySQL always stores TIMESTAMP fields in UTC internally (that's the definition of a unix timestamp, in fact). So when you SELECT or UPDATE/INSERT/REPLACE, the time you get or set is always in the MySQL server's local time zone.
So a common mistake is to store UTC_TIMESTAMP(), which MySQL interprets as a local time and so the current time gets double-converted to UTC when it stores it internally in the field as a unix TIMESTAMP.

Categories