converting UTC to local time automatically using PHP - php

Im using MySQL with PHP, and the project is a kind of notification manager
if some one does some thing, a new notification need to be posted in the common post-ground
the issue is - we have users from multiple timezones, currently Im using "datetime" as the field type, so what ever I enter converts into UTC
for example: Im from India(+5:30) and if I create a notification at 21/3/2015 22:50:00, it is saving in DB as 21/3/2015 17:20:00
storing works perfectly well from all zones, but while retrieving it shows for me as 21/3/2015 17:20:00(UTC) but Im expecting in my timezone(IST +5:30) so what Im expecting is 21/3/2015 22:50:00.
is there a way to mention in the query itself to get the time converted in the fetching itself?
or any other way to convert and process further?
any help on this is greatly appreciated.
Thank you

You can use the function convert_tz so while selecting you can use the following
mysql> select convert_tz('2015-03-21 17:20:00','+00:00','+05:30') as ist_time;
+---------------------+
| ist_time |
+---------------------+
| 2015-03-21 22:50:00 |
+---------------------+
1 row in set (0.00 sec)
All you need to do is to change the hard coded date '2015-03-21 17:20:00' to your column name in the selection.

You can get your client TimeZone through JSTZ
In your php file, you can simply convert the date after you received the from mysql:
$date = new DateTime($date . " " . "UTC");
$date->setTimezone(new DateTimeZone($timeZoneTo));//$timeZoneTo you get it from JSTZ

Related

Converting CURDATE() to my local date with MySQL

I'm using Godaddy's MySQL database. Since their timezone is MST UTC -7, I needed to modify my code. I figured out how to do it when using NOW() function. However Im struggling while converting result of CURDATE() to my local date. Topics in the website didnt help it. I dont have privilege to change timezone of mysql since it is shared host. The problem about CURDATE() is, since there is 10 hours difference between server and my country, dates will be different at somepoint.
What I have tried so far
First attempt
SELECT convert_tz(CURDATE(),'-07:00','+03:00')
this query returns following output in the mysql.
convert_tz(CURDATE(),'-07:00','+03:00')
2016-05-14 10:00:00
I didnt try yet since still dates are the same but this code probably done the work. But the problem is about the time comes after date.CURDATE should return only date. I think it returns the differences between two timezones which equals to 10 hours but I think it is gonna cause problem when Im comparing 2 dates.
Second attempt
SELECT convert_tz(CURDATE(),'MST','EEST');
Since server's timezone is MST and my timezone is EEST, I tried in this way but it returns NULL.
The question is what should I do to just return date without that 10:00:00 there. or is there any better way?
There are a couple of problems with your approach.
First, CURDATE() returns a date, not a datetime.
Second, you need to convert the current date and time from the server's time zone to your time zone before truncating the time portion. This means using NOW() inside, not CURDATE().
Third, you need to use the correct abbreviations for the correct time zones for both sides of the conversion, for the entire year. CONVERT_TZ() will return NULL if either time zone is unrecognized.
In this case, MST/MDT is called "MST7MDT" and EET/EEST is called "EET" in the MySQL time zone tables. It's surprising that Go Daddy doesn't set their server clocks to UTC -- that's sort of a de facto standard for server clocks, but assuming not, "MST7MDT" is probably the most correct value.
mysql> SELECT DATE(CONVERT_TZ(NOW(),'MST7MDT','EET'));
+-----------------------------------------+
| DATE(CONVERT_TZ(NOW(),'MST7MDT','EET')) |
+-----------------------------------------+
| 2016-05-14 |
+-----------------------------------------+
1 row in set (0.00 sec)
Or, you could use the more intuitive localized names for the time zones. I believe these values would also be correct, an would accommodate summer and time changes correctly:
mysql> SELECT DATE(CONVERT_TZ(NOW(),'America/Denver','Europe/Bucharest'));
+-------------------------------------------------------------+
| DATE(CONVERT_TZ(NOW(),'America/Denver','Europe/Bucharest')) |
+-------------------------------------------------------------+
| 2016-05-14 |
+-------------------------------------------------------------+
1 row in set (0.00 sec)
Try to convert you date into string using CAST, and then get a substring.
SELECT SUBSTRING_INDEX( CAST(CONVERT_TZ(CURDATE(),'-07:00','+03:00') AS char), ':', -1)
Should return
2016-05-14 10:00

PHP/MySQL randomly failed to parse the correct datetime

I'm getting an issue with datetime when inserting to the MySQL. I cannot tell if it was caused by PHP, Apache server or MySQL server which parsed the datetime to "1969-12-31 18:00:00". It happens vey randomly. While everyone has no problem insert the PHP date to MySQL, one or two users failed to get a proper datetime value from the same code. Those users are not consistent.
In PHP:
$thetime = date('Y-m-d H:i:s');
So, I guess there is nothing wrong with that line, unless the server returns the wrong datetime.
I'm using MyISAM. I also suspect MyISAM caused the problem if 2 clients inserting 2 records at the same time.
It could be Apache server is not doing its job properly. It might return the wrong datetime.
My question is that how I point out what caused the problem.
you can check the variables as recommended in here
mysql> show variables like 'date%format';
+-----------------+-------------------+
| Variable_name | Value |
+-----------------+-------------------+
| date_format | %Y-%m-%d |
| datetime_format | %Y-%m-%d %H:%i:%s |
+-----------------+-------------------+
2 rows in set (0.00 sec)
source: https://serverfault.com/questions/313400/datetime-format-changed-between-mysql-5-0-and-5-1

How to properly insert time values in mysql using php framework laravel 5.1?

Actually, I'm trying to insert some 'time' values in mysql database using laravel 5.1 eloquent. But I'm getting that ZERO time error.
I insert some time, like '06:55:00' and in the database shows '00:00:00'.
So, I want to understand the better practices to insert datetime values and avoid this kind of errors.
Here the actual code that I'm working on:
$some_var = ModelClass::create([
'time1' => date('H:m:s', strtotime('06:30:00')),
'time2' => date('H:m:s', strtotime('14:55:00'))
])->pluck('id');
And I got this in the database:
id | time1 | time2 |
1 | 00:00:00 | 00:00:00 |
Thanks to samlev
Using Carbon solved my problem, and looks like a good way to work with DateTime values.
If anybody else is has problems with another kind of php framework, maybe could use it too.
just access carbon's page here.

Bulk convert log file date time format from 12 hour clock to 24 hour clock for mySQL database

I am creating a web app to analyze data from a client's custom database. I am having difficulty finding a way how to convert the client's log file entries from 12 hour clock to 24 hour clock. The Database that I am setting this up with cannot read 12 hour time format, so is displaying the time wrong.
Log files I am using look like this:
Site_Name,number_of_clicks,DD/MM/YYYY_2:00PM,Interaction_Type
I need to convert the log files to look like this:
Site_Name,number_of_clicks,DD/MM/YYYY_14:00,Interaction_Type
There are tens of thousands of enteries per log file, so there is no way this can be done per entry. I need to figure out a way to bulk convert the entries to 24-hour clock for each of the log files.
Any help would be greatly appreciated!
Thanks!
Aaron
If you want to do that on db side and you use MySql you can read it with STR_TO_DATE() and either use it as a datetime value
INSERT INTO log (`Site_Name`, `number_of_clicks`, `date`, `Interaction_Type`)
SELECT 'site1', 10, STR_TO_DATE('10/05/2013_2:00PM', '%d/%m/%Y_%l:%i%p'), 1;
or
UPDATE log
SET date = STR_TO_DATE(str_date, '%d/%m/%Y_%l:%i%p');
assuming that date column is of type datetime, and str_date column contains string values in 12h format.
or if for some reason you store it as VARCHAR and really need to format it as DD/MM/YYYY_14:00 then you can use DATE_FORMAT()
DATE_FORMAT(STR_TO_DATE('10/05/2013_2:00PM', '%d/%m/%Y_%l:%i%p'), '%d/%m/%Y_%k:%i')
which will produce
| NEWDATE |
--------------------
| 10/05/2013_14:00 |
To update in-place
UPDATE log
SET str_date = DATE_FORMAT(STR_TO_DATE(str_date, '%d/%m/%Y_%l:%i%p'), '%d/%m/%Y_%k:%i');
Here is SQLFiddle demo.
Why don’t you write a simple app that will search through all log entries and update whenever it finds date in PM format.
You basically need to write a piece of code that will add 12 hrs if there is PM in the time.
Here is a rough code in C#... not fully tested but you can build on this…
protected string ConvertToPM(string logEntry)
{
string result = string.Empty;
//DD/MM/YYYY_2:00PM
if (logEntry.Contains("PM"))
{
string temp = logEntry.Substring(logEntry.IndexOf("_"), logEntry.IndexOf(":") - logEntry.IndexOf("_"));
result = logEntry.Replace(temp, (Convert.ToInt32(temp) + 12).ToString());
}
return result;
}
Just add a piece of code that will a) read log file line by line b) extract date part c) use function similar to the one above to alter the data…

Timestamp, Date, Time, or DateTime which is which?

I know that this is longed asked question but still I can't find an answer.
I have a fix time in and out in my database.
Also I have date_in and date_out in separate columns.
All the data in my database come from csv which is in that exact format.
Can I concatenate (time_in and date_in) and (time_out and date_out) and put them in a designated column which is in timestamp format?
I'm making a import and export of csv in which those info below is concern. So far I can export it but
my import doesn't work well. I use the phpmyadmin csv load data to import. Can't get my head in importation of dates and times coz other data mess up in my database.
Note: total_hrs is not included in the csv which means that it is already in my database. And it doesn't have a value so basicaly I will provide values for that in my script.
Example:
id | time_in | time_out | date_in | date_out | total_hrs
1 | 9:30pm | 7:30am | 2013-12-01 | 2013-13-01 | ?
This should have a 10 hours elapsed time.
So basically it also has a different date.
I'm confused whether I need to convert the time in timestamps or something similar to get the time difference or I also need to have the date as well to be a basis in getting the difference between the two time??Any suggestions.
It could be also 34, 58,.. hours. I advise you to store timestamps, if you will need pretty display of it you can just use print (or smth similiar) function in MySql.
If you have the date you should use timestamps. They're easier to compare.
use timestamps in mysql:
INSERT INTO tblTimes (timein) VALUES (NOW());
UPDATE tblTimes SET timeout = NOW() WHERE id=$someid;
to compare, see https://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_timediff

Categories