Question: How do I Display a UTC timestamp from a database table in a users local time? Is there any way to do this with php?
Extra Context \/
I have an application that saves the date records are added to the database.I am saving the records in the database using mysql UTC_TIMESTAMP(). I then want to display the record to the user in their local time in my Smarty template.
{$dateAdded|smarty_modifier:"%D %R %Z"}
I have tried smarty, date_format as the modifier but I just get the UTC time and the persons timezone, which of course is correct but not the result that I want.
02/11/11 20:32 Pacific Standard Time
I need the time so be set to the user's local time
02/11/11 12:32 Pacific Standard Time
Is it correct to store the date of the transaction in UTC, and how do I display that UTC to the user in their local time? Is there a way to pull the date out of the database so that it is set to the users current local time?
You can use date_default_timezone_set() prior invoking the Smarty template. That defines directly how the UTC timestamps are adapted to the expected output timezone.
Related
I am using timestamp fields in my databases and my PHP software has its own time management system based on users timezone. I want to use timestamp fields for certain kind of data (created or modified when) and also be able to use te DEFAULT CURRENT_TIMESTAMP for the columns.
Is there any disadvantage setting the timezone to UTC using, SET time_zone = '+00:00', each time the session is created. I have four separate databases which the software uses and currently, I am setting the current timezone to UTC.
I don't want to use DATETIME as they are larger in size and also I won't be able to use DEFAULT CURRENT_TIMESTAMP as the timezone of the server might have an offset.
You should not use SET time_zone if your backend already uses all the logic into converting user's timezone correctly, because you're wasting resources unnecessarily. The UTC timezone should be into the metadata of the DB, where always the DB transactions will work with them.
By the way, TIMESTAMP columns always will be stored in UTC, so you don't need to setting that, unless your columns are datetime (not the case, i think).
When you insert a TIMESTAMP value, MySQL converts it from your
connection’s time zone to UTC for storage. When you query a TIMESTAMP
value, MySQL converts the UTC value back to your connection’s time
zone. Notice that this conversion does not occur for other temporal
data types such as DATETIME.
So you have two options:
Set the timezone in your transactions working with time in your sql;
Working with unix timezones into backend and only showing the correct converted time in the frontend to user.
I prefer the second one.
When dealing with date/time for entry date and/or modified date, it is better to use normal VARCHAR with the length of around 200 (or any other value that fits the full date) in order to store the full date and process your date/time in your PHP script. This gives you the flexibility to view your time based on the timezone defined in your PHP code. Click here to see available timezones in PHP.
You can also format the date/time in any possible format you want by simply using the date_format of PHP.
I have given a reference code below.
//This is the way you define your timezone in PHP code
date_default_timezone_set('Asia/Beirut');
//You can capture the date/time by using the below code. This will store "2017-05-28 23:55:34"
$date_time_registered = date('Y-m-d H:i:s');
//Retrieve the date/time and re-format it as you require. Below code will output "May", full month.
$retrieve_month_only = date_create($row['your_store_date_time']);
$retrieve_month_formatted = date_format($retrieve_month_only, 'F');
echo $retrieve_month_formatted;
You can refer to this link to find out about PHP date/time formatting.
I want to store a Carbon date time object in a MySQL Database and I am using Laravel Eloquent to do this.
I have build a test with different data types (dateTime, dateTimeTz, timestamp and timestampTz from Laravel Migrations) and every one cuts off the time zone and only stores the date and time. When the data is accessed again Laravel assumes the default time zone from config and I have invalid data.
Is there a way to either preserve the time zone or to automatically convert the date and time to UTC or the config time zone?
MySQL doesn't provide any features to store Timestamp with Timezone. You have to separately maintain all the timezone manually.
You can define seprate column for maintaining the timezone when the Timestamp retrieved from the Database you can convert Timestamp to related Timezone.
For that you can use Laravel features Accessors.
I have a created a timestamp in MySQL that changes when an account is updated by a users, and this timestamp is echoed on the page. However it is displaying the server time rather than my local time. I can't set the timezone in MySQL, I tried. What is another way to change this, and how can it be implemented?
The problem with timestamp datatype is that
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. The
time zone can be set on a per-connection basis. As long as the time
zone setting remains constant, you get back the same value you store.
If you store a TIMESTAMP value, and then change the time zone and
retrieve the value, the retrieved value is different from the value
you stored.
So, it does not really matter what your timezone setting in php is, you need to set either mysql's timezone on a session basis using
SET time_zone = timezone
command, or you need to store the timezone of the client along with the timestamp and adjus the value based on the stored timezone. I would use the latter approach, since a client technically can change timezones and if the client access the timestamp data from a different timezone, then different data will be returned by mysql.
When echoing from a database add in some "filters" seemed to do the trick
<?php echo $row['field name']; strtotime(date("Y-m-d", 1310571061)); ?>
Without the above code it displayed the timestamp as: 2016-02-09 00:00:00
With the above code it displays thus: Tuesday, February 09, 2016
I'm working on some website (news portal) in PHP and MySQL. I have a rubric last post with time when news are posted. My timezone and server timezone is GMT+2. I want to display a time correctly to all clients from all time zones. Example, if news is posted at 13:05 at my timezone to display for clients from GMT+3 14:05, for clients from GMT+4 zone 15:05, for GMT+1 12:05, and so on. How to do that? What is solution and what is a best way to store date and time in MySQL database for that purpose? I'm also integrate Carbon in my website but I can't find method for that.
What we do in our company is we store all times in GMT. Even though we are in South-Africa. Then based on the user's location we convert the time to display correctly. There are a number of ways to determine where a user is located and convert the time, however the easiest method is to just ask them where they live and store that information.
Keep dates in timestamp.
Store timezones for all clients.
After establishing connection to database run query like that:
SET ##session.time_zone = "+02:00";
or
SET ##session.time_zone = "Europe/Warsaw";
Where timezone offset or name is value stored for client.
All timestamp values will be returned from queries in defined timezone.
While storing values in db store in UTC timezone something like below
date_default_timezone_set('UTC');
Then while displaying the values get the user timezone using any timezone js and send the timezone to server using ajax and store it in SESSION variable and while displayin the date add that timezone.
For example
1)Download the timezone js from https://bitbucket.org/pellepim/jstimezonedetect/src
Following will give you the timezone
var tz = jstz.determine(); // Determines the time zone of the browser client
var timezone=tz.name(); // Returns the name of the time zone eg "Europe/Berlin"
Make ajax call like below
$.post("scripts/set_timezone.php", { timezone: timezone} );
and in set_timezone.php have code
session_start();
$_SESSION['user_timezone'] = $_POST['timezone'];
and while displaying display as follows
$date = new DateTime('2012-01-23 05:00:00', new DateTimeZone('UTC'));
$date->setTimezone(new DateTimeZone($_SESSION['user_timezone']));//This will from the session e.g Asia/Kolkata
$time= $date->format('Y-m-d H:i:s');
I have built a small forum where users can post messages. My server is in the United States, but the userbase for the forum is in Taiwan (+15hrs).
When someone posts to the form, I store the time in my mySQL database in the format YYYY-MM-DD HH:MM:SS. When I look in the database, the time displays the proper time (the time that the person in Taiwan posted it).
However, when I use UNIX_TIMESTAMP to get the date out of the database, the time is altered.
Example:
I post something to the forum. The datetime on my wrist watch is 2009-10-2 11:24am (Taiwan Time)
I look in the database and it says the datetime is 2009-10-2 11:24am (same time as my wrist watch. good!)
Then when I use UNIX_TIMESTAMP to display the date on my website, it shows as 2009-10-03 4:22 pm (bad! it applied an offset)
Is there a way I can get UNIX_TIMESTAMP to stop converting the time (applying an offset) when I query the date from the database?
Extra Info:
I'm using PHP
I have set the timezone in my PHP to Taiwan (date.timezone = Asia/Taipei)
If a user is in another timezone than Taiwan, I want it to convert the time to Taipei time. The site is nearly 100% Taiwan used so I just want Taiwan time to show all the time even if they're in another timezone.
I display the date in lots of areas around the site in different date() formats.
Basically everything works great except that when I use UNIX_TIMESTAMP to query the data out, it applies an offset to the time.
Thanks!
MySQL writes dates "as-is", also reads them so, but UNIX_TIMESTAMP treats any input dates as in your local timezone and converts them to UTC/GMT timestamps meaning it will apply your local timezone offset, now if you process your timestamps returned from mysql via eg. php date() it will again apply your local timezone offset(note there is also gmtime() which does not do that), which will produce unwanted results.
But you can get by with this following trick which will subtract your session timezone before UNIX_TIMESTAMP() applies it, so you will get the exact number regardless of the server/local timezone if you want the exact same date in db as if it were a GMT time.
mysql> SELECT UNIX_TIMESTAMP(CONVERT_TZ("2013-05-27","GMT",##session.time_zone));
+--------------------------------------------------------------------+
| UNIX_TIMESTAMP(CONVERT_TZ("2013-05-27","GMT",##session.time_zone)) |
+--------------------------------------------------------------------+
| 1369612800 |
+--------------------------------------------------------------------+
1 row in set (0.00 sec)
Another solution would be to set the servers or session timezone to 0(GMT), so there will be no real conversions taking place.
MySQL takes system's default timezone setting unless told otherwise, it explains the problems you are having; take a look at MySQL's time zone reference manual for more details. Based on my past experience I've come to a conclusion UTC is the best choice for storing date and time; when displaying it to the user, they are converted to user's timezone.
If possible, change all date and time entries in the DB to UTC, configure timezone in PHP usingdate_default_timezone_set()and make sure to convert it properly when rendering it to the user and when storing it in the database as well. If storing UTC values is not an option, you may simply convert them by following time zone reference guide the same way as with UTC.
What you need to do is grab raw date and time from the database and then use PHP's DateTime to convert it. Take a look at DateTimeZone as well.
The best that I have found to this problem is using this:
SELECT UNIX_TIMESTAMP(CONVERT_TZ(<<>>,'+15:00','+00:00')) +TIMESTAMPDIFF(second,utc_timestamp(), now())
Example: I want to get the timestamp of 31-may-2012 at 23:59:59, Local time.
SELECT UNIX_TIMESTAMP(CONVERT_TZ('2012-05-31 23:59:59','+15:00','+00:00')) +TIMESTAMPDIFF(second,utc_timestamp(), now())
This way I get the timestamp GMT-0, corresponding to the localtime.
I have found a possible solution which is to just retrieve the date from the database without converting it to Unix time, and then just using strtotime(); to convert it to Unix time. Basically instead of converting using sql, i'm converting using php. The only things I don't like about it are: strtotime() < I'm not sure how reliable this function is, and I have to go and change about 100 places where i'm using UNIX_TIMESTAMP (doh!)
Are there any other ways?