Dealing with timezones in PHP and MySQL - php

I am trying to understand what exactly is responsible for changing and converting timezones and time respectively in my application stack and what is the best way to go about converting time to the required timezone in application code.
I am currently using:
Javascript/HTML font end
Laravel PHP framework server side
MySQL storage (Defaults to local system time for timestamps etc.)
I am of the opinion that:
MySQL can't store timezones for DateTime columns and just stores YYY:MM:DD hh:mm:ss and it's up to the developer to store the timezone in a separate column etc. and convert the stored time to user local in application code if user timezone is different.
A PHP, Laravel application should work in and convert any DateTime instances to the timezone set with date_default_timezone_set() function.
The behaviour I am currently observing:
I post back json with object properties set with javascript date time format. This format looks like so for me: e.g. 'Thu Jun 16 2016 18:00:00 GMT+1000 (AEST)'
When this json data hits my server, the application framework or PHP automatically converts it to UTC, even if I put date_default_timezone_set('Australia/Sydney') in controller class or change application configuration, replacing the laravel UTC default. I suspect something is not registering ? If I was able to save time as it came from the client (without being automatically converted to UTC), I would not have to later convert it to the user local time zone if the user is in Australia/Sydney (which is most of them).
My application stores this UTC adjusted time in the database, without actually having any record that it is UTC. Not really important of course as I can presume default of UTC.
When records are retrieved with eloquent or DB:query, there's no automatic conversion to user timezone and it simply returns the time as it was stored (converted to UTC), requiring application code to convert it to correct timezone, else user (in Australia in my case) will be looking at UTC time as opposed to local AEST Etc.
Converting time:
Is there a hassle free way of automatically converting all retrieved UTC time from the database to the user local timezone or some specified default time zone if all users are presumed from the same timezone ?
Ideally I want to pull out records from the database and have all the time properties adjusted to specified timezone, taking daylight savings into account. Would I have to run a for loop and convert/set each property with Carbon methods etc. ?
If the date_default_timezone_set('Australia/Sydney') is set and working properly, should PHP be automatically converting the time property on all those objects as they are retrieved from the database ? As well as not converting time data to UTC when it hits the server ?

timezones are annoying, there's no doubt about that. If I'm understanding you correctly, you want your PHP to return times to the view that are in the correct zone for the user, right?
What I do is within the 'master view' or some sort or blade.php file that is guaranteed to be loaded at least once, I check whether or not this user's timezone is stored in a session variable. If it is not, I send an AJAX request to the server to store the name of the timezone.
{{-- store timezone in session variables --}}
#if (!Session::has('timezone'))
<script>
$(function () {
var tz = jstz.determine();
var data = {};
if (typeof (tz) !== 'undefined') {
data.timezone = tz.name();
}
if (!$.isEmptyObject(data)) {
$.ajax({
type: "POST",
url: "{{ url('/api/v1/settings') }}",
beforeSend: function (request) {
request.setRequestHeader("X-CSRF-TOKEN", "{{ csrf_token() }}");
},
data: $.param(data),
});
}
});
</script>
#endif
Note that this approach utilizies the jstz package, which you can download here and include in your <head> section.
Of course you will need to set up the route for this request, for my case, it looks like this:
Route::post('api/v1/settings', function () {
// Save the user's timezone
if (Request::has('timezone')) {
Session::put('timezone', Request::get('timezone'));
}
});
Now, when you want to convert the given database datetime strings to the correct timezone, you can get the timezone by saying $tz = $request->session()->get('timezone') and then parse out the dates with Carbon\Carbon::parse($date, $tz);
In general, I would recommmend you stay with storing all dates in UTC format, as that is the standard and it is imperitive that the database remain timezone agnostic. But if you want to change the default, you can edit the line 'timezone' => 'UTC' in config/app.php. That will overwrite the zone that Laravel defaults its timestamps to, so your created_at, updated_at will be changed to reflect that new timezone.

Agh - the good old "what to do with timezones" issue. Personally, on one of my L5.2 projects that heavily requires user timezone formatting for displaying data. I allow the user to select/modify their timezone on an account settings page. I then store this in a database and set up relationships for retrieving. For instance, I have many users who belong to one company. So in my "companies" table, I have a timezone field here. With proper relationships, I can access it like so Auth::user()->company->timezone
Then I parse all dates relevant to the platform using Carbon. For example, $current_date = Carbon:parse($date, Auth::user()->company->timezone);.
In hindsight, if I wasn't lazy (have other priorities) and wouldn't need to update a bunch of code, I'd probably create a trait for my models to convert the date attributes automatically.
Honestly though, there's many ways - and it can be a tricky thing to figure out if your platform is heavily on user timezones.
For example, you could do something like this in each of your models (or create a trait - best option - to store this). Note, I used my timezone relationship as an example. Obviously change "some_date" etc to whatever you table name is. Repeat as needed for each date you need converted:
/**
* Convert date to user's timezone
*
* #return mixed
*/
public function setSomeDateAttribute($value)
{
$this->attributes['some_date'] = Carbon::parse($value, Auth::user()->company->timezone);
}
Note, dates should always be stored in database as UTC. Never save a user's timezone formatted date in database.

I'm not going into the discussion of how timestamp works but lemme tell you how efficiently you can store date time in MySQL to use it further. And why should you use a specific pattern to store time zone if you storing it for the very first time
date_default_timezone_set('Asia/Kolkata');
$live_date = date('Y-m-d H:i:s');
Advantages of using this timestamp are-
You can directly specify data-type as DATETIME in the MySQL database while creating the table. It will allow you to sort data with this column as well.
Not just in the database but if you'll be using jQuery Data tables in your front-end, you'll get an advantage here too as this also allows sorting with time.
While writing a SQL query to fetch data for a particular date/time range, this way of storing time works well and you can simply write
BETWEEN date1 AND date2

Related

How to handle user's timezone and UTC sync between application and database in CakePHP?

I need to display dates and times in user's timezone. But I also need to save dates and times in UTC, so my database stay consistent.
My cakephp application configured like this:
In config/app.php file:
'Datasources' => [
'default' => [
...
'timezone' => 'UTC',
In config/bootstrap.php file:
/*
* Set server timezone to UTC. You can change it to another timezone of your
* choice but using UTC makes time calculations / conversions easier.
*/
date_default_timezone_set('UTC');
In my application, a user can change his timezone whenever he wants. It's then saved in database and available as $this->Account->timezone in controllers, and $account->timezone in views.
So let's say my database is consistent and all my datetimes are stored in UTC, so when user type in a date, it's converted to UTC (from his timezone).
Now I want to display these dates. I get them from my database in UTC. For now I use the method from Cakephp (where $item is an entity and date is an attribute of this entity):
$item->date->i18nFormat('dd/MM',$user->timezone),
With this function I can easily display datetimes in the format I want, and in the timezone I want.
Is there a way to set $user->timezone to the entire app, so I don't need to specify it each time ?
Thanks.
Your question reads as if you're already handling the timezone conversion when saving user supplied dates, so I'll stick to the display part.
Use the time helper
As stated in the comments, there's nothing wrong with explicitly passing the timezone whenever it is required, however if you'd really need to adjust the timezone for (mostly) everything you output in your view templates, then take a look at the (kind of undocumented) time helper's outputTimezone option.
$this->loadHelper('Time', ['outputTimezone' => $user->timezone]);
Then use the helper's i18nFormat() method and you should be good with regards to timezone conversion:
$this->Time->i18nFormat($item->date, 'dd/MM');
Configure a global string format
It's also possible to globally configure the output format via the \Cake\I18n\DateFormatTrait::setToStringFormat()
and \Cake\Chronos\Traits\FormattingTrait::setToStringFormat() methods, which are available on the Date/Time/FrozenDate/FrozenTime/Chronos classes accordingly.
The following would for example cause all "date only" objects to be formatted as dd/MM when being converted to a string, being it through implicit casting, or explicit formatting when calling for example i18nFormat() without passing a specific format:
\Cake\I18n\Date::setToStringFormat('dd/MM');
See also
Cookbook > Views > Helpers > Configuring Helpers
Cookbook > Date & Time > Setting the Default Locale and Format String

Web and Database server settings to get UTC timezone "right"

I'm overwhelmed trying to get this right: We've got servers located across a dozen time zones, with Apache and MySQL running on all or some of them, as well as MySQL hosted on Amazon RDS.
I want to know "Best Practices", or how to otherwise configure each MySQL and PHP installation so that when a row is added to the database from PHP I'm certain that the value there is actually the UTC time when the event happened, regardless of where the server is located when it happened. Presenting it to the user in any given timezone is not an issue - I just want to know that the datetime columns are actually storing the actual moment in time when something occurred.
As it is now, the Web Servers are set to whatever the local timezone is due to scheduled events, etc., and I'm not sure which parts of the puzzle use which settings from where to come up with whatever is written to the database.
I apologize if the question seems unclear, at this point I don't know what I don't know, so getting a precise question is even challenging. Also, all our dates are in the database as DateTime fields, so storing timestamps isn't possible.
If you restrict yourself to MySQLs DATE and DATETIME types, you can largely ignore time zone issues in MySQL itself. You want to avoid MySQL's TIMESTAMP type because:
MySQL converts TIMESTAMP values from the current time zone to UTC for storage, and back from UTC to the current time zone for retrieval. (This does not occur for other types such as DATETIME.) By default, the current time zone for each connection is the server's time.
https://dev.mysql.com/doc/refman/5.7/en/datetime.html
As far as reading/writing DATETIME values, you'll get back exactly what you put in, which is good.
That leaves you with the problem of always ensuring you are writing UTC values to the database.
The best way to ensure that PHP is using UTC is to explicitly set it in your application using date_default_timezone_set(). That will ensure that calls like date('Y-m-d H:i:s') will give you the UTC value. It will also ensure that something like (new \DateTime('now'))->getTimezone() will return a UTC \DateTimeZone instance.
You should note, of course, that things get significantly more difficult when you're storing date/time values that you take from users. In those cases, you'll need to somehow determine what timezone the user is in, and handle conversion to UTC before persisting the values. Assuming your users have some per-user timezone setting, you basically do something like:
/** #var \DateTimeZone $userTZ */
$userTz = getUserTimezone();
$dateTime = new \DateTime($user_submitted_date_string, $userTz);
$dateTime->setTimezone(new \DateTime('UTC'));
$dateTimeStr = $dateTime->format('Y-m-d H:i:s');
Quite simple, always store unix time in the database (or if you want microsecond accuracy with microtime ). Then regardless of the timezone of each of your webservers, if two of them recieve a request at the same time, it would be the same integer value that is saved in the database (the database field shoudl obviously be an int (or big int for micro time))
And how to display? Easy with javascript.
new Date(unix_timestamp);
This produces a date and time in the user's timezone.

Timezone offset issue

Working on a mod where a user inputs a datetime in this format "11/28/2012 11:34 am".
I am then using strtotime to convert it to a timestamp and saving it to my database.
I am then displaying it to the user in my template using the following date(DateTime, 'D M jS g:i A').
The problem is users who are not in the same timezone as the user who created the event do not get the correct time updated to reflect their timezone.
I have access to both timezone offset's of the user posting and the user viewing.
MY question is how should I compensate for timezone differences?
When converting the string to the real timezone use this to override server time zone with time zone of the user submitting the value: http://us3.php.net/manual/en/function.date-default-timezone-set.php
When retrieving it later, use the same function to override server time zone to current user's one (the one that is appropriate for the user displaying datetime at the moment).
Also make sure you store it properly in the database: preferably using Unix timestamps within PHP, TIMESTAMP columns within database, FROM_UNIXTIME() database function when saving to the database and UNIX_TIMESTAMP() when retrieving from database (all are valid for MySql RDBMS, check your own DBMS if it is different).

Using time zones in a PHP web application

I've been looking around for a few hours now about what's the best way to use timezones in a PHP/MySQL web application, finding a definitive answer is hard. From what I've learnt so far it is best to store everyones stuff in the database in UTC (correct me if I am wrong).
When a user registers I will ask them for there timezone and then store that against there user. This would be in this format as a dropdown menu:
<option value="Europe/London">(GMT) Greenwich Mean Time : London</option>
The app I am building will allow users to set arrangements in the future with people (meetings), much like a calendar. Obviously over the course of a year different timezones have different daylight savings periods, any idea how I would cater for this?
Say a user from the UK sets a meeting for 3:00PM on January 24th 2013 and invites someone who lives in California to this meeting, how do I get it so that the American sees that meeting in his/her timezone and the UK user sees it in his/her timezone? (Note that both users are signed up and have set their timezone).
Does anyone have a clear explanation and maybe some examples for this? Or can point me to where I can find that?
Thanks
I dealt with this situation extensively in a PHP/MySQL application I wrote for a private jet operator a little over a year ago. There are different strategies to handle timezones in these two platforms, but I will explain how I did it. I set the MySQL server to UTC and run each PHP script in the timezone that the user specifies during the signup process for the user profile.
MySQL and PHP (PHP 5.2 and above) both have native datetime datatypes. MySQL's datetime is a primitive data type, while PHP 5.2 and above offers the built-in DateTime class. The MySQL datetime datatype does not include metadata for the timezone, but a PHP DateTime object always includes a timezone. If the PHP datetime constructor does not specify the optional timezone in the second argument, then the PHP datetime constructor uses the php environment variable.
Both MySQL and PHP have default timezone set in the configuration files. MySQL uses the datetime set in the config file for each db connection unless the user specifies a different timezone after connection is started with the command SET time_zone = [timezone];. PHP also sets a timezone environment variable for each script using the timezone set in the server config file, and this environment variable can be overriden using the PHP function date_default_timezone_set() after the script starts.
The PHP DateTime class has a property called timezone, which is a PHP DateTimeZone object. The DateTimeZone object is specified using a string for the exact time zone. The list of timezones is comprehensive, having hundreds of individual time zones across the world. The PHP time zones will account for daylight savings time automatically.
When the user generates a datetime in the web app, construct a PHP datetime object in the timezone of the user's profile. Then use the setTimezone method to modify the DateTime object to the UTC timezone. Now you have the user's datetime in UTC, and you can store the value in the database. Use the DateTime format method to express the data as a string in the format accepted by MySQL.
So the user generates a datetime, and you make a PHP datetime object in the user's specified timezone:
// set using an include file for user profile
$user_timezone = new DateTimeZone('America/New_York');
// 1st arg in format accepted by PHP strtotime
$date_object1 = new DateTime('8/9/2012 5:19 PM', $user_timezone);
$date_object1->setTimezone(new DateTimeZone('UTC'));
$formated_string = $date_object1->format('Y-m-d H:i:s');
$query_string = "INSERT INTO `t_table1` (`datetime1`) VALUES('$formated_string')";
When you retrieve the value from the database, construct in UTC and then convert to the user's time zone.
$query_string = "SELECT `datetime1` FROM `t_table1`";
$date_object1 = new DateTime($datetime_string_from_mysql, new DateTimeZone('UTC'));
$date_object1->setTimezone($user_timezone);
$string_for_display_in_application = $date_object1->format('m/d/Y g:i a');
Using this method, your datetime values are always stored in UTC inside the db, and the user always experiences the values in his/her profile's time zone. PHP will correct for Daylight Savings Time if necessary for each time zone.
One gotcha: This explanation does not cover the MySQL timestamp datatype. I recommend using the MySQL datetime datetype to store datetime values, not the timestamp datatype. The timestamp datatype is covered in the manual here.
Edit:
You can produce an array containing every PHP timezone string using listIdentifiers, which is a static method of the DateTimeZone class.
In MySQL, what you need to do is:
Store each user's chosen timezone someplace you can retrieve it when you're doing database queries on behalf of that user. You can store it as a string.
Right before you do work on behalf of a particular user (for example, storing or retrieving appointment times and dates) do SET time_zone = (stored time zone setting)
This will cause time zones to be converted appropriately to each person's local time.
Edit:
This works because
MySQL tries to use UTC (universal time, formerly known as Greenwich Mean Time) to store DATETIME and TIMESTAMP data items in tables.
It can only do this correctly if it knows the correct local time zone for each data item it is given by applications.
In applications that don't care about different time zones, it does this in a MySQL-server-wide way. See https://dev.mysql.com/doc/refman/5.5/en/time-zone-support.html . Most people who run multi-national and multi-time-zone applications set their server time zones to UTC, not to local time, because it makes it much easier to keep things sorted out.
It makes very little sense to try to convert a time from UTC to local time unless you also know the date and the timezone, because local time switches on and off at various times of year. Just try to get this right for all three of Israel, Arizona, and New York, I dare you! Israel switches between daylight and standard time on Passover and Rosh Hashanah; Arizona doesn't switch, and New York switches at the whim of the US federal legislature.
There's a session-scope time_zone setting (SET time_zone = something). If you don't set it, it uses the timezone representation in item 3 above. If you set it, the server will use this as the timezone to convert its internal representation to the representation it sends back in queries.
You can get a list of the names of the available time zones in your MySQL server by issuing SELECT Name from mysql.time_zone_name. This can populate the pulldown menu from which your user can select her time zone. If this query returns no items, take a look at bottom of https://dev.mysql.com/doc/refman/5.5/en/time-zone-support.html .
So, that means you can set your session time_zone setting to a particular user's time zone, and then get back all times in that user's time zone. Also, any DATETIME or TIMESTAMP items you INSERT or UPDATE will be converted from that user's time zone to MySQL's internal representation as they are placed in your tables.
Be careful: in web applications with persistent MySQL connections, the work for a new user request will inherit the connection's time_zone setting. Don't forget to reset it for the new user.
If you're running a query returning local time data for more than one user, and those users happen to be in different time zones, you can't take advantage of this MySQL per-session feature set. You can work around this by running different queries for different users and changing the time_zone setting between them.
Or, you can use the MySQL function
CONVERT_TZ(datetime,'UTC','user_time_zone')
or similar on each item.
Alternatively, Java and DotNET have their own high-quality time zone manipulation systems. So, you can make the choice of running your MySQL server with the time_zone setting of UTC, and do all your timezone conversions in your application.

PHP, Codeigniter: How to Set Date/Time based on users timezone/location globally in a web app?

I have just realised if I add a particular record to my MySQL database - it will have a date/time of the server and not the particular user and where they are located which means my search function by date is useless! As they will not be able to search by when they have added it in their timezone rather when it was added in the servers timezone.
Is there a way in Codeigniter to globally set time and date specific to a users location (maybe using their IP) and every time I call date() or time() that users timezone is used.
What I am actually asking for is
probably how to make my application
dependent on each users timezone?
Maybe its better to store each users timezone in their profile and have a standard time (servers time) and then convert the time to for each user?
Thanks all
It sounds like what you need to do is store all of the date and times in your system as UTC time (used to be called GMT). This is the base time that everything in the world is calculated off of with adjustments. (eg: Central Time is -6 hours off of UTC)
In MySQL you can use UTC_TIMESTAMP() to get the current UTC time as long as your server and DB are configured with the correct times and timezone settings.
In PHP run this to set the timestamp of PHP to UTC (you will run this in your code so put it on every page or in a centralized index file):
date_default_timezone_set('UTC');
Or you can go directly into PHP.INI and tell it to use UTC time globally. (this may not work if you have multiple websites on a single installation of PHP.
And then anywhere in the system you need to get the current UTC time you can just call:
time();
Then for each user in the system you will need to ask them what timezone they live in and then when you display times make the adjustment for that user. So if it is 5:00PM UTC and I live in Easter US (-5) the time would be 5:00 - 5 hours = 12:00PM.
This can be a long process to get right but once you do your users will find it very useful especially internationally.
I think the easiest way is define a timezone for internal data storage (your server's time zone or UTC) and convert the time according to the user's time zone when outputting it.
I don't know CodeIgniter so I can't point you to the right functions. One prominent library that is timezone aware is Zend_Date: Working with Timezones I have not worked with these functions yet but they look promising.
However, once you know the user's time zone, it's not difficult to put together an own function that adds/substracts the offset when outputting dates and/or times.
Possibly related question:
MySQL: keep server timezone or user timezone?
Take an example of an existing web application such as WordPress and phpBB. Each user have their own timezone setting.
When receiving a content from the user, use local_to_gmt() function in the Date Helper then save the content into database using the gmt date. When fetching the data you will get the time in gmt. Get the user's timezone setting, then display the data in that timezone.
This way, you can save yourself from calculating between two timezone. Just make sure that your server's time is in correct setting, so all your data is in the correct gmt time.
UPDATE:
Recently I review the last project I worked on that have timezone issue. After thinking various scenario, here is the solution for the timezone issue:
All data stored right now already
using server's time. Changing this
will takes times and prone to error,
so I leave it like that.
For the new data from user that set the content date to a certain
date and time, I stored it into 2
column. First column is to store the
data as is, and used to displaying
it as is. Second column will be a
recalculation of the date based on
the user's timezone into server's
timezone. This column is used in the
WHERE statement (filter based on
server date) and for the ORDER
(because this column's value all in
same timezone, which is the server's
timezone).
This way, I only do 1 timezone calculation, which is to convert user date into server date. For displaying , I display the date according to server's datetime. Since all data stored in the same timezone, data can be ordered by the column that hold the server date value.
For the user that have set their timezone, the date from database can be easily recalculated to get the datetime in the user's timezone. Btw, in my application, I display the date using timeago jquery plugins. This plugins need time in the ISO8601 format (UTC time). local_to_gmt() function in CodeIgniter can be used to do this.
Obviously the leap to British Summer Time (Daylight Savings Time) is a big confusion in the world of programming, and I am indeed caught up in that confusion.
The best possible solution I can find (which I will try to coherently explain) when using a timezone sensitive system is this:
The Web Server and Database should both be running off the same machine timezone. I suggest UTC as it is the building blocks of timezone conversions. This will ensure that all of the dates stored in your database are constant, and don't skip any times such as the 1hour jump between Daylight Savings.
At the top of all of your PHP scripts use date_default_timezone_set('Europe/London'); with the specific timezone of the user.
When producing dates from user submitted forms, use gmmktime(); to ensure that the timestamp created is UTC and not altered by the timezone that you have set.
date(); can be used when displaying dates, as this will convert the timestamp to the correct time taking into account the timezone that you have set.
If you do need to show a date in the UTC format then use gmdate(); with the $gm_timestamp that you have taken from the database or created with gmmktime();.
I have written this bit of PHP to help understand the situation.
date_default_timezone_set('UTC');
$gmtime = gmmktime(2,0,0,03,29,2009);
$time = mktime(2,0,0,03,29,2009);
echo $gmtime.'<br />'.date('r',$gmtime).'<br />'.gmdate('r',$gmtime).'<br />';
echo $time.'<br />'.date('r',$time).'<br />'.gmdate('r',$time).'<br />';
date_default_timezone_set('Europe/London');
$gmtime = gmmktime(2,0,0,03,29,2009);
$time = mktime(2,0,0,03,29,2009);
echo $gmtime.'<br />'.date('r',$gmtime).'<br />'.gmdate('r',$gmtime).'<br />';
echo $time.'<br />'.date('r',$time).'<br />'.gmdate('r',$time).'<br />';
Hopefully I've done a good job, but I doubt it because I'm still trying to battle the problem in my head.
UPDATE:
Glad I did this, because I am now having doubts about the user inputted dates.
To get the User inputted date (taking into account their timezone) to match up with the UTC corresponding date in the database, you should put it through mktime(). And then use gmdate('U', $timestamp); to get the true UTC timestamp. (I think)
Example
Looking at it from a reporting side, the user is using the 'Europe/London' timezone. At the start of our PHP script we call date_default_timezone_set('Europe/London');, whilst the Database (and all the records within) is still in UTC.
The user then sends through that they want to select a list of books added to the database between 25/03/2010 10:00 to 30/03/2010 14:00. The PHP script then runs the date variables through mktime($hour, $minute, $second, $month, $day, $year) to generate a correct UTC timestamp. The start date will not change, but PHP knows that the end date is within the BST timezone, so changes the timestamp to UTC accordingly.
When the results are returned back to the user, date('r', $date_added) can be used to show the user the date the book was added to the database according to their set timezone.
This link may help with understanding when it changes. http://www.daylightsavingtime.co.uk/
I think recalculating to user's time is better option, since it gives you normalized time on server, i.e. if you'll need to look up something, that happened (from your point of view) hour ago, you won't have a mess with american, asian and e.g. australian time.
Just ask them for their timezone (usually select with major cities in that timezone) and then recalculate :)
Or, alternatively, you can store two timedates - one for your comparison and one to show, so you won't have so much calculations on serverside.
Also, if recalculating, you can use date helper:
http://ellislab.com/codeigniter/user-guide/helpers/date_helper.html
I've used the MySQL built-in timezone conversion. In the database, all datetimes are stored as UTC. In the select query, I used CONVERT_TZ to convert to the user's timezone. You can specify timezone codes or hour invervals like:
SELECT CONVERT_TZ('2004-01-01 12:00:00','GMT','MET');
SELECT CONVERT_TZ('2004-01-01 12:00:00','+00:00','+10:00');
But, the problem is this does not accommodate for daylight savings times. This is particularly frustrating since many parts of the world either don't honor daylight savings or honor it on different dates. So, if you install the timezone description tables, you can use descriptive names that will account for daylight savings automatically like:
SELECT CONVERT_TZ('2004-01-01 12:00:00', 'UTC', 'US/Eastern');
Codeigniter contains a helper which deals with all manner of date functions.
Codeigniter Date helper
the command gmt_to_local() should help you... the third parameter is for 'daylight_saving'.
Takes a Unix timestamp (referenced to GMT) as input, and converts it to a localized timestamp based on the timezone and Daylight Saving time submitted. Example:
$timestamp = '1140153693';
$timezone = 'UM8';
$daylight_saving = TRUE;
echo gmt_to_local($timestamp, $timezone, $daylight_saving);
Add this line to autoload.php in the application folder/config folder:
$autoload['time_zone'] = date_default_timezone_set('Asia/Kolkata');

Categories