Convert MySQL UTC datetime to UNIX timestamp - php

These both correctly return the current UNIX timestamp:
SELECT UNIX_TIMESTAMP(LOCALTIMESTAMP()); #MySql
echo time(); //PHP
But I'm storing UTC_TIMESTAMPs in my database (not LOCALTIMESTAMPs).
How can I convert a UTC datetime to a UNIX timestamp using MySQL?

Note that LOCALTIMESTAMP() is a synonym for NOW(). So what you're really asking is how to get the current time and convert it to GMT and then convert to a unix timestamp to store in the db. So this will work:
SELECT UNIX_TIMESTAMP(CONVERT_TZ(NOW(), ##global.time_zone, 'GMT'));
As an aside, it's always much better to use the time and date columns of a database rather than unix timestamps. It makes querying and displaying results much easier.
Update: Are you sure you are getting what you think you are? UNIX_TIMESTAMP returns a UTC based seconds since the UNIX epoch. It does not return a MySQL DateTime type. If you have an actual UTC DateTime instance, then you can put that directly into your DateTime column of your database and don't have to use UNIX_TIMESTAMP as an intermediary. What type do you actually have that's in local time?

Related

PHP: Convert epoch to MySQL DateTime format

I have to store epoch timestamps into a MySQL database DateTime column. I need to be able to convert the epoch into the DateTime form to be able to add it to the database. The epoch data is grabbed from an external source so we have no control over that, the database is also established and should be left as it is. We just need to be able to convert between the two in PHP.
PHP
date("Y-m-d H:i:s",$epochTS);
MySQL
FROM_UNIXTIME(timestampColumn)
Nothing more to it
No need to do any convert for MySQL or PHP just or enter the same to database
echo date('r', $epoch);
strotime() is the function used to convert datetime to epoch. Documentation
strotime() is the function used to convert datetime to epoch. Documentation
time() is the function used to convert epoch to datetime. Documentation

PHP & MySQL Timezones whilst supporting user-defined timezones

I'm working on something where the user can select their own timezone and the software will be able to be used by others on their sites as well but I want to make sure that the timezone within the database is always set to UTC.
Now I know how you set the default timezone for PHP, such as:
date_default_timezone_set('Australia/Sydney');
...but I'm not sure how to make sure MySQL is using UTC? ...and even once you have made sure it is using UTC I guess you would have to convert your PHP dates/times into UTC before passing it to the database?
I guess I am wondering about many different date formats such as TIMESTAMP, DATETIME & even UNIX EPOCH integer timestamps which would simply be stored as a int datatype for example.
Then there is the whole retrieving dates/times from the DB and converting it to the respective timezone and lastly how does DST come into all of this?
I know there is a lot of similar questions out there, but I guess none really answered all my questions.
MySQL's data type timestamp stores the dates in UTC. For this to work properly, MySQL uses server's time zone and does the date conversion. It converts the date from servers's current time zone to UTC for storage. This implies that the database server should never change its time zone for this feature to work properly.
When you send the data to such a database, you send the UTC time as well. The easiest way to do this is to format a result of time() according to what MySQL wants (m-d-Y H:i:s).
In PHP, when you format the date for insertion to MySQL, it's the best to use DateTime class. It lets you offset the date with the time zone information, meaning that you don't have to use date_default_timezone_set function - that can lead to mistakes.
An example of DateTime in action:
$date = '1.12.2015 13:37:37'; // Format is day.month.year hour:minute:second
// We create DateTime from custom date format, for the person who resides in Australia/Sydney time zone
$dt = DateTime::createFromFormat('d.m.Y H:i:s', $date, new DateTimeZone('Australia/Sydney');
// Now we change the date's time zone into UTC, and we can insert it into MySQL
$dt->setTimeZone(new DateTimeZone('UTC'));
// This is the formatted date-string that can be safely inserted into MySQL
$date_string_for_mysql = $dt->format('m-d-Y H:i:s');
Alternatively, you can use int type in MySQL for timestamp storage and insert result of time() but this has a huge disadvantage of not being able to use date-related functions.
for current session of mysql you can try something like
SET time_zone = timezonename;
for more details you can also look into this answer https://dba.stackexchange.com/questions/20217/mysql-set-utc-time-as-default-timestamp

mysql timestamp not in epoch

I've set a field in my mysql db to "timestamp" yet it still returns time in queries as yyyy:mm:dd: time. I set it as a timestamp because I wanted milliseconds since 1970. How do I achieve this ?
What language are you using? In PHP, you can convert a MySQL timestamp to seconds from the epoch using the function strtotime. You could also, if absolutely desperate, use string parsing to get each part of the timestamp and calculate the seconds from the epoch yourself.
Just store the Unix timestamp as an INT. Then when you call it from the DB you can process it server side to get what you want.

php timestamp utc

I have a PHP MySQL query that inserts some data into a MySQL database and it includes a timestamp.
Currently the INSERT query uses NOW() for the the timestamp column and it is saved in the database in the following format: 2012-07-24 13:13:02
Unfortunately for me the Server is not in my time zone and it is listed as America/Los_Angeles as shown print date_default_timezone_get();
I was hoping to do the following:
date_default_timezone_set('Europe/London');
$timefordbLondonEU = date('Y-m-d H:i:s', time());
and simply save into the database the $timefordbLondonEU in place of the NOW();
Is this a good way to save such data ?
Many Thanks,
Richard
[ADDED TEXT]
I changed the Type in the MySQL db to DateTime and did the following:
date_default_timezone_set('Europe/London');
$timefordbLondonEU = date('Y-m-d H:i:s', time());
It is working but Im still not getting the overall concept yet.
Assumptions based on your comments:
MySQL = Does not have a datatype UTC you simply use type INT.
Unix_TimeStamp() will save the current time or count? in UTC format such as 1343247227.
As UTC is a count from a common 0 point you can get any timezone from it. Assuming that you don't want a date before the reference 0 point in 1970.
My guess and lead on from what you have said is the best way to do it is save the time as UTC in an INT (1343247227) and then generate any time zones you want from there. Again assuming you don't need to store dates before the reference 0 point in 1970.
Equally why not store as datetime YYYY-MM-DD HH:MM:SS at a known timezone and then convert to UTC or other timezones. It all seems pretty messy =(
As #Petah said in the comments, store your times in UTC and covert them in the application as needed.
Unix timestamps are in UTC so I usually store my times in the database as timestamps. This saves the headache and confusion of first converting to UTC to insert, and then from UTC when selecting.
That is, make your time field an INT type, and use the function UNIX_TIMESTAMP() in MySQL when you insert, or get the timestamp from PHP using the time() function.
When you fetch the timestamp from the DB it will be in UTC, but when you display it in your PHP application using date(), it will display in the server timezone, or whatever you set with date_default_timezone_set.
Therefore the following two queries will work:
INSERT INTO `table` (id, time) VALUES(NULL, UNIX_TIMESTAMP());
// or
$time = time();
$query = "INSERT INTO `table` (id, time) VALUES(NULL, $time);
If you want to select it from the DB as a DATETIME, you can do this:
SELECT *, FROM_UNIXTIME(time) as dt FROM `table` WHERE 1
The resulting dt column will be in the format yyyy-MM-dd hh:mm:ss.
You can format the numeric timestamp in PHP using date()
If the PHP version you have is 64-bit, you aren't limited to the 1970 - 2036 range, PHP will support 64-bit timestamps, just make sure to use a BIGINT column in MySQL in that case.
Hope that helps.

MySQL convert DateTime (storing a UTC_TIMESTAMP) to number of seconds 1970

There are many similar questions out there but I believe this one is unique. (Sorry if it isn't)
Our database has datetime field named "date_sampled", of which we store with UTC_TIMESTAMP()
Our goal is to return the number of seconds since 1970. I noticed UNIX_TIMESTAMP() if supplied no argument returns the current UNIX_TIMESTAMP() and if a datetime (i.e. 2011-10-10) is passed, it returns a timestamp in seconds.
However UTC_TIMESTAMP() does not work like this, it Only returns a current UTC Timestamp.
So how can I convert my DateTime field (holding a UTC datetime) into the seconds from 1970 in MySQL? If it can't be done in MySQL, then a PHP solution will work.
Thanks.
There is a TIMESTAMPDIFF function in MySQL, you can use it something like
SELECT TIMESTAMPDIFF(SECOND,'1970-01-01 00:00:00', YourUTCDateFromSomewhere)
More details in the docs - http://dev.mysql.com/doc/refman/5.1/en/date-and-time-functions.html#function_timestampdiff
What were you trying to get UTC_TIMESTAMP to do that UNIX_TIMESTAMP doesn't? Unix timestamps are in UTC by definition.
I'm assuming the problem you're having is that, even though you're storing your datetimes in UTC, UNIX_TIMESTAMP is giving you a timezone-offset result, so you're getting a value several hours off from what you're expecting.
UNIX_TIMESTAMP respects MySQL's time_zone variable, so if all your dates are in UTC, you can just set your session's time_zone variable to UTC, which will cause UNIX_TIMESTAMP to do no timezone conversion when converting a datetime to a timestamp.
SET time_zone = '+00:00'
Interesting problem... I have no clue how to do this with SQL... but the PHP solution would be to use the strtotime() function..
<?php
echo strtotime('2011-10-10');
?>
The above example returns the value 1318219200 which is the number of seconds that have passed since the 1970 epoch

Categories