Mysql Unix_timestamp function - mysql

In oracle converting this date 2012-07-03 11:38:41 to unix_timestamp we get
select (to_date('2012-07-03 11:38:41','YYYY-MM-DD HH24:MI:SS') -
to_date('1970-01-01 00:00:00','YYYY-MM-DD HH24:MI:SS'))*86400 as unix_timestamp
from dual
SQL> /
UNIX_TIMESTAMP
--------------
1341315521
But when i try the same on mysql server
select UNIX_TIMESTAMP('2012-07-03 11:38:41')
1341311921
Server Settings are something like this
**mysql**> select current_timestamp();
+---------------------+
| current_timestamp() |
+---------------------+
| 2012-07-26 15:27:31 |
+---------------------+
1 row in set (0.00 sec)
**Unix** >Thu Jul 26 15:27:56 BST 2012
**oracle**>select current_timestamp from dual;
CURRENT_TIMESTAMP
------------------------------------
26-JUL-12 15.27.16.967258 +01:00
How do i make sure oracle and mysql give me the same values ?

The difference between the two values you show is 3600 seconds, i.e. 1 hour.
Most likely, the two servers' timezone settings vary by one hour.
See https://dev.mysql.com/doc/refman/5.5/en/time-zone-support.html for time zone info in the mySQL server. Here is some in-depth info for Oracle's handling of time zones.

I used this trick
unix_timestamp(cast(sys_extract_utc(systimestamp) as date
And then i also wrote a function called unix_timestamp
create or replace
function unix_timestamp(in_date date)
return number DETERMINISTIC PARALLEL_ENABLE AS
l_date date;
begin
return trunc((in_date -to_date ( '01-jan-1970', 'dd-mon-yyyy' ))*86400);
end;
/

Related

How to save records in MYSQL db with CURRENT_TIMESTAMP in UTC format and NOT LOCALTIME?

Save records with column as 'created_date' which has CURRENT_TIMESTAMP which should be UTC time and not local time
UTC_TIMESTAMP() function
In MySQL, the UTC_TIMESTAMP returns the current UTC date and time as a value in YYYY-MM-DD HH:MM:SS or YYYYMMDDHHMMSS.uuuuuu format depending on the usage of the function i.e. in a string or numeric context.
Note : Since UTC_TIMESTAMP() works on current datetime, your output may vary from the output shown.
Syntax: UTC_TIMESTAMP; UTC_TIMESTAMP()
Code: SELECT UTC_TIMESTAMP,UTC_TIMESTAMP();
Sample Output:
mysql> SELECT UTC_TIMESTAMP,UTC_TIMESTAMP();
+---------------------+---------------------+
| UTC_TIMESTAMP | UTC_TIMESTAMP() |
+---------------------+---------------------+
| 2015-04-14 22:52:11 | 2015-04-14 22:52:11 |
+---------------------+---------------------+
1 row in set (0.01 sec)
My solution is with a trigger:
DELIMITER //
CREATE TRIGGER `update_to_utc` BEFORE INSERT ON `my_table` FOR EACH ROW BEGIN
set new.my_field=utc_timestamp();
END//
DELIMITER ;

Is CURRENT_TIMESTAMP - updated_time same as TIMESTAMPDIFF(SECOND, updated_time, CURRENT_TIMESTAMP )

I wrote a sql to calculate time diff between now and last updated time. Firstly I just use CURRENT_TIMESTAMP - updated_time and found the result looks like correct in time unit second. But it wasn't stable, sometimes the result went to much bigger that correct one. And then I changed to TIMESTAMPDIFF(SECOND, updated_time, CURRENT_TIMESTAMP ) , everything is OK. My question is what's the difference of tow expressions?
The CURRENT_TIMESTAMP() or CURRENT_TIMESTAMP are synonyms for NOW() which gives your current time.
Edit2:
After your additional comment I understood what you are asking. (I have deleted the first edit) which was incomplete and somewhat incorrect.
The question is: "To explain inner workings of CURRENT_TIMESTAMP - updated_time."
The explanation (I went way deeper):
The CURRENT_TIMESTAMP can return date and time in 'YYYY-MM-DD HH:MM:SS' or YYYYMMDDHHMMSS format.
What maybe confused you is that it can return either string or numeric value based on the context.
Here you have a numeric context as you have the - (minus) operator.
`String context`
SELECT CURRENT_TIMESTAMP();
-> '2017-07-04 08:50:26'
OR
`numeric context`
SELECT NOW() + 0;
-> 20170704085026
The - (minus) operator only appears to work:
mysql> insert into temp (first, second)
-> VALUES ('2017-07-01 03:00:00', '2017-07-01 03:01:00');
Query OK, 1 row affected (0.00 sec)
mysql> select first, second, second - first from temp;
+---------------------+---------------------+----------------+
| first | second | first - second |
+---------------------+---------------------+----------------+
| 2017-07-01 03:00:00 | 2017-07-01 03:00:37 | 37.000000 |
| 2017-07-01 03:00:00 | 2017-07-01 03:01:00 | 100.000000 |
+---------------------+---------------------+----------------+
2 rows in set (0.00 sec)
Oh nice! 100 seconds in a minute? I don't think so! :).
To correctly subtract your time (if updated_time is in seconds):
The TIME_TO_SEC is needed: TIME_TO_SEC(CURRENT_TIMESTAMP) - updated_time

MySql unix_time() function with only date argument

Ok, so the following works fine
mysql> SELECT UNIX_TIMESTAMP('2007-11-30 10:30:19');
But if I give only a date argument, like in:
mysql> SELECT UNIX_TIMESTAMP('2007-11-30');
Then somehow I am getting the timestamp equivalent to 2007-11-30 18:30 GMT. Can I somehow reset it to give timestamp for the beginning of that particular day? Like UNIX_TIMESTAMP('2007-11-30'); should give the timestamp equivalent of UNIX_TIMESTAMP('2007-11-30 00:00:00'); I need to filter out some records from a table based an event that happend after a certain date.
Thanks
[EDIT]: I don't know how but this seems to be working as expected now. Screenshots: 2007-11:30 00:00:00 2007-11:30 18:30:00 2007-11:30
I have checked it But i am getting same timestamp for '2007-11-30 00:00:00' and '2007-11-30'
mysql> SELECT UNIX_TIMESTAMP('2007-11-30 00:00:00');
+---------------------------------------+
| UNIX_TIMESTAMP('2007-11-30 00:00:00') |
+---------------------------------------+
| 1196361000 |
+---------------------------------------+
1 row in set (0.00 sec)
mysql> SELECT UNIX_TIMESTAMP('2007-11-30');
+------------------------------+
| UNIX_TIMESTAMP('2007-11-30') |
+------------------------------+
| 1196361000 |
+------------------------------+
Can you run these queries on your machine and check timestamp values.
I also checked, for me as well it is giving for 00:00:00. On further investigation, I came across this Here:
The server interprets date as a value in the current time zone and
converts it to an internal value in UTC. Clients can set their time
zone as described in Section 10.6, “MySQL Server Time Zone Support”.
On further searching, it became apparent that there is a variable system_time_zone, that is set when server starts using server machine's timezone. See here also
For each client connecting, they can set their own timezone as
mysql> SET time_zone = timezone;
So finally, you need to check your system_time_zone, set it to proper value.
I hope it will work well then....
Found a way to make sure, that the UNIX_TIMESTAMP function returns the correct timestamp irrespective of anything interfering with the timezone etc
>> SELECT UNIX_TIMESTAMP(CONCAT(t.DATE,' 00:00:00')) FROM db.table_name t
That is, to append the 00:00:00 manually in the query string.

CURRENT_TIMESTAMP in milliseconds

Is there any way to get milliseconds out of a timestamp in MySql or PostgreSql (or others just out of curiosity)?
SELECT CURRENT_TIMESTAMP
--> 2012-03-08 20:12:06.032572
Is there anything like this:
SELECT CURRENT_MILLISEC
--> 1331255526000
or the only alternative is to use the DATEDIFF from the era?
For MySQL (5.6+) you can do this:
SELECT ROUND(UNIX_TIMESTAMP(CURTIME(4)) * 1000)
Which will return (e.g.):
1420998416685 --milliseconds
To get the Unix timestamp in seconds in MySQL:
select UNIX_TIMESTAMP();
Details: http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_unix-timestamp
Not tested PostgreSQL, but according to this site it should work: http://www.raditha.com/postgres/timestamp.php
select round( date_part( 'epoch', now() ) );
In mysql, it is possible to use the uuid function to extract milliseconds.
select conv(
concat(
substring(uid,16,3),
substring(uid,10,4),
substring(uid,1,8))
,16,10)
div 10000
- (141427 * 24 * 60 * 60 * 1000) as current_mills
from (select uuid() uid) as alias;
Result:
+---------------+
| current_mills |
+---------------+
| 1410954031133 |
+---------------+
It also works in older mysql versions!
Thank you to this page: http://rpbouman.blogspot.com.es/2014/06/mysql-extracting-timstamp-and-mac.html
The main misunderstanding in MySQL with timestamps is that MySQL by default both returns and stores timestamps without a fractional part.
SELECT current_timestamp() => 2018-01-18 12:05:34
which can be converted to seconds timestamp as
SELECT UNIX_TIMESTAMP(current_timestamp()) => 1516272429
To add fractional part:
SELECT current_timestamp(3) => 2018-01-18 12:05:58.983
which can be converted to microseconds timestamp as
SELECT CAST( 1000*UNIX_TIMESTAMP(current_timestamp(3)) AS UNSIGNED INTEGER) ts => 1516272274786
There are few tricks with storing in tables. If your table was created like
CREATE TABLE `ts_test_table` (
`id` int(1) NOT NULL,
`not_fractional_timestamp` timestamp NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
than MySQL will NOT store fractional part within it:
id, not_fractional_timestamp
1, 2018-01-18 11:35:12
If you want to add fractional part into your table, you need to create your table in another way:
CREATE TABLE `ts_test_table2` (
`id` int(1) NOT NULL,
`some_data` varchar(10) COLLATE utf8mb4_unicode_ci NOT NULL,
`fractional_timestamp` timestamp(3) NULL DEFAULT CURRENT_TIMESTAMP(3) ON UPDATE CURRENT_TIMESTAMP(3),
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
that leads to required result:
id, some_data, fractional_timestamp
1, 8, 2018-01-18 11:45:40.811
current_timestamp() function is allowed to receive value up to 6, but I've found out (at least in my installed MySQL 5.7.11 version on Windows) that fraction precision 6 leads to the same constant value of 3 digits at the tail, in my case 688
id, some_data, fractional_timestamp
1, 2, 2018-01-18 12:01:54.167688
2, 4, 2018-01-18 12:01:58.893688
That means that really usable timestamp precision of MySQL is platform-dependent:
on Windows: 3
on Linux: 6
In Mysql 5.7+ you can execute
select current_timestamp(6)
for more details
https://dev.mysql.com/doc/refman/5.7/en/fractional-seconds.html
Poster is asking for an integer value of MS since Epoch, not a time or S since Epoch.
For that, you need to use NOW(3) which gives you time in fractional seconds to 3 decimal places (ie MS precision): 2020-02-13 16:30:18.236
Then UNIX_TIMESTAMP(NOW(3)) to get the time to fractional seconds since epoc:
1581611418.236
Finally, FLOOR(UNIX_TIMESTAMP(NOW(3))*1000) to get it to a nice round integer, for ms since epoc:
1581611418236
Make it a MySQL Function:
CREATE FUNCTION UNIX_MS() RETURNS BIGINT DETERMINISTIC
BEGIN
RETURN FLOOR(UNIX_TIMESTAMP(NOW(3))*1000);
END
Now run SELECT UNIX_MS();
Note: this was all copied by hand so if there are mistakes feel free to fix ;)
Use:
Select curtime(4);
This will give you milliseconds.
The correct way of extracting miliseconds from a timestamp value on PostgreSQL accordingly to current documentation is:
SELECT date_part('milliseconds', current_timestamp);
--OR
SELECT EXTRACT(MILLISECONDS FROM current_timestamp);
with returns: The seconds field, including fractional parts, multiplied by 1000. Note that this includes full seconds.
Easiest way I found to receive current time in milliseconds in MySql:
SELECT (UNIX_TIMESTAMP(NOW(3)) * 1000)
Since MySql 5.6.
None of these responses really solve the problem in postgreSQL, i.e :
getting the unix timestamp of a date field in milliseconds
I had the same issue and tested the different previous responses without satisfying result.
Finally, I found a really simple way, probably the simplest :
SELECT ROUND(EXTRACT (EPOCH FROM <date_column>::timestamp)::float*1000) as unix_tms
FROM <table>
namely :
We extract the pgSQL EPOCH, i.e. unix timestamp in floatting seconds from our column casted in timestamp prudence (in some complexe queries, pgSQL could trow an error if this cast isn't explicit. See )
then we cast it in float and multiply it by 1000 to get the value in milliseconds
then we round it to drop the fractional part
In PostgreSQL you can use :
SELECT extract(epoch from now());
on MySQL :
SELECT unix_timestamp(now());
Here's an expression that works for MariaDB and MySQL >= 5.6:
SELECT (UNIX_TIMESTAMP(NOW()) * 1000000 + MICROSECOND(NOW(6))) AS unix_now_in_microseconds;
This relies on the fact that NOW() always returns the same time throughout a query; it's possible that a plain UNIX_TIMESTAMP() would work as well, I'm not sure based on the documentation. It also requires MySQL >= 5.6 for the new precision argument for NOW() function (MariaDB works too).
Postgres: SELECT (extract(epoch from now())*1000)::bigint;
In MariaDB you can use
SELECT NOW(4);
To get milisecs. See here, too.
In PostgreSQL we use this approach:
SELECT round(EXTRACT (EPOCH FROM now())::float*1000)
For mysql:
SELECT (UNIX_TIMESTAMP() * 1000) AS unix_now_in_microseconds; --- 1600698677000
I felt the need to continue to refine, so in MySQL:
Current timestamp in milliseconds:
floor(unix_timestamp(current_timestamp(3)) * 1000)
Timestamp in milliseconds from given datetime(3):
floor(unix_timestamp("2015-04-27 15:14:55.692") * 1000)
Convert timestamp in milliseconds to datetime(3):
from_unixtime(1430146422456 / 1000)
Convert datetime(3) to timestamp in milliseconds:
floor(unix_timestamp("2015-04-27 14:53:42.456") * 1000)
For everyone here, just listen / read the comments of Doin very good! The UNIX_TIMESTAMP() function will, when a datatime-string is given, contact a local time, based on the timezone of the MySQL Connection or the server, to a unix timestamp. When in a different timezone and dealing with daylight savings, one hour per year, this will go wrong!
For example, in the Netherlands, the last Sunday of October, a second after reaching 02:59:59 for the first time, the time will be set back to 02:00:00 again. When using the NOW(), CURTIME() or SYSDATE()-functions from MySQL and passing it to the UNIX_TIMESTAMP() function, the timestamps will be wrong for a whole our.
For example, on Satudray 27th of October 2018, the time and timestamps went like this:
Local time | UTC Time | Timestamp | Timestamp using MYSQL's UNIX_TIMESTAMP(NOW(4))
----------------------------------+---------------------------+--------------+-----------------------------------------------------
2018-10-27 01:59:59 CET (+02:00) | 2018-10-26 23:59:59 UTC | 1540598399 | 1540598399
2018-10-27 02:00:00 CET (+02:00) | 2018-10-27 00:00:00 UTC | 1540598400 | 1540598400 + 1 second
2018-10-27 02:59:59 CET (+02:00) | 2018-10-27 00:59:59 UTC | 1540601999 | 1540601999
2018-10-27 03:00:00 CET (+02:00) | 2018-10-27 01:00:00 UTC | 1540602000 | 1540602000 + 1 second
2018-10-27 03:59:59 CET (+02:00) | 2018-10-27 01:59:59 UTC | 1540605599 | 1540605599
2018-10-27 04:00:00 CET (+02:00) | 2018-10-27 02:00:00 UTC | 1540605600 | 1540605600 + 1 second
But on Sunday 27th of October 2019, when we've adjusted the clock one hour. Because the local time, doensn't include information whether it's +02:00 or +01:00, converting the time 02:00:00 the first time and the second time, both give the same timestamp (from the second 02:00:00) when using MYSQL's UNIX_TIMESTAMP(NOW(4)) function. So, when checking the timestamps in the database, it did this: +1 +1 +3601 +1 +1 ... +1 +1 -3599 +1 +1 etc.
Local time | UTC Time | Timestamp | Timestamp using MYSQL's UNIX_TIMESTAMP(NOW(4))
----------------------------------+---------------------------+--------------+-----------------------------------------------------
2019-10-27 01:59:59 CET (+02:00) | 2019-10-26 23:59:59 UTC | 1572134399 | 1572134399
2019-10-27 02:00:00 CET (+02:00) | 2019-10-27 00:00:00 UTC | 1572134400 | 1572138000 + 3601 seconds
2019-10-27 02:59:59 CET (+02:00) | 2019-10-27 00:59:59 UTC | 1572137999 | 1572141599
2019-10-27 02:00:00 CET (+01:00) | 2019-10-27 01:00:00 UTC | 1572138000 | 1572138000 - 3599 seconds
2019-10-27 02:59:59 CET (+01:00) | 2019-10-27 01:59:59 UTC | 1572141599 | 1572141599
2019-10-27 03:00:00 CET (+01:00) | 2019-10-27 02:00:00 UTC | 1572141600 | 1572141600 + 1 second
Relaying on the UNIX_TIMESTAMP()-function from MySQL when converting local times, unfortunately, is very unreliable! Instead of using SELECT UNIX_TIMESTAMP(NOW(4)), we're now using the code below, which seams to solve the issue.
SELECT ROUND(UNIX_TIMESTAMP() + (MICROSECOND(UTC_TIME(6))*0.000001), 4)
Mysql:
SELECT REPLACE(unix_timestamp(current_timestamp(3)),'.','');
I faced the same issue recently and I created a small github project that contains a new mysql function UNIX_TIMESTAMP_MS() that returns the current timestamp in milliseconds.
Also you can do the following :
SELECT UNIX_TIMESTAMP_MS(NOW(3)) or SELECT UNIX_TIMESTAMP_MS(DateTimeField)
The project is located here : https://github.com/silviucpp/unix_timestamp_ms
To compile you need to Just run make compile in the project root.
Then you need to only copy the shared library in the /usr/lib/mysql/plugin/ (or whatever the plugin folder is on your machine.)
After this just open a mysql console and run :
CREATE FUNCTION UNIX_TIMESTAMP_MS RETURNS INT SONAME 'unix_timestamp_ms.so';
I hope this will help,
Silviu
Do as follows for milliseconds:
select round(date_format(CURTIME(3), "%f")/1000)
You can get microseconds by the following:
select date_format(CURTIME(6), "%f")

How do I get the current time zone of MySQL?

Anyone knows if there is such a function in MySQL?
UPDATE
This doesn't output any valid info:
mysql> SELECT ##global.time_zone, ##session.time_zone;
+--------------------+---------------------+
| ##global.time_zone | ##session.time_zone |
+--------------------+---------------------+
| SYSTEM | SYSTEM |
+--------------------+---------------------+
Or maybe MySQL itself can't know exactly the time_zone used,that's fine, we can involve PHP here, as long as I can get valid info not like SYSTEM...
From the manual (section 9.6):
The current values of the global and client-specific time zones can be retrieved like this:
mysql> SELECT ##global.time_zone, ##session.time_zone;
Edit The above returns SYSTEM if MySQL is set to use the system's timezone, which is less than helpful. Since you're using PHP, if the answer from MySQL is SYSTEM, you can then ask the system what timezone it's using via date_default_timezone_get. (Of course, as VolkerK pointed out, PHP may be running on a different server, but as assumptions go, assuming the web server and the DB server it's talking to are set to [if not actually in] the same timezone isn't a huge leap.) But beware that (as with MySQL), you can set the timezone that PHP uses (date_default_timezone_set), which means it may report a different value than the OS is using. If you're in control of the PHP code, you should know whether you're doing that and be okay.
But the whole question of what timezone the MySQL server is using may be a tangent, because asking the server what timezone it's in tells you absolutely nothing about the data in the database. Read on for details:
Further discussion:
If you're in control of the server, of course you can ensure that the timezone is a known quantity. If you're not in control of the server, you can set the timezone used by your connection like this:
set time_zone = '+00:00';
That sets the timezone to GMT, so that any further operations (like now()) will use GMT.
Note, though, that time and date values are not stored with timezone information in MySQL:
mysql> create table foo (tstamp datetime) Engine=MyISAM;
Query OK, 0 rows affected (0.06 sec)
mysql> insert into foo (tstamp) values (now());
Query OK, 1 row affected (0.00 sec)
mysql> set time_zone = '+01:00';
Query OK, 0 rows affected (0.00 sec)
mysql> select tstamp from foo;
+---------------------+
| tstamp |
+---------------------+
| 2010-05-29 08:31:59 |
+---------------------+
1 row in set (0.00 sec)
mysql> set time_zone = '+02:00';
Query OK, 0 rows affected (0.00 sec)
mysql> select tstamp from foo;
+---------------------+
| tstamp |
+---------------------+
| 2010-05-29 08:31:59 | <== Note, no change!
+---------------------+
1 row in set (0.00 sec)
mysql> select now();
+---------------------+
| now() |
+---------------------+
| 2010-05-29 10:32:32 |
+---------------------+
1 row in set (0.00 sec)
mysql> set time_zone = '+00:00';
Query OK, 0 rows affected (0.00 sec)
mysql> select now();
+---------------------+
| now() |
+---------------------+
| 2010-05-29 08:32:38 | <== Note, it changed!
+---------------------+
1 row in set (0.00 sec)
So knowing the timezone of the server is only important in terms of functions that get the time right now, such as now(), unix_timestamp(), etc.; it doesn't tell you anything about what timezone the dates in the database data are using. You might choose to assume they were written using the server's timezone, but that assumption may well be flawed. To know the timezone of any dates or times stored in the data, you have to ensure that they're stored with timezone information or (as I do) ensure they're always in GMT.
Why is assuming the data was written using the server's timezone flawed? Well, for one thing, the data may have been written using a connection that set a different timezone. The database may have been moved from one server to another, where the servers were in different timezones (I ran into that when I inherited a database that had moved from Texas to California). But even if the data is written on the server, with its current time zone, it's still ambiguous. Last year, in the United States, Daylight Savings Time was turned off at 2:00 a.m. on November 1st. Suppose my server is in California using the Pacific timezone and I have the value 2009-11-01 01:30:00 in the database. When was it? Was that 1:30 a.m. November 1st PDT, or 1:30 a.m. November 1st PST (an hour later)? You have absolutely no way of knowing. Moral: Always store dates/times in GMT (which doesn't do DST) and convert to the desired timezone as/when necessary.
The query below returns the timezone of the current session.
select timediff(now(),convert_tz(now(),##session.time_zone,'+00:00'));
Simply
SELECT ##system_time_zone;
Returns PST (or whatever is relevant to your system).
If you're trying to determine the session timezone you can use this query:
SELECT IF(##session.time_zone = 'SYSTEM', ##system_time_zone, ##session.time_zone);
Which will return the session timezone if it differs from the system timezone.
As Jakub Vrána (The creator or Adminer and NotORM) mentions in the comments, to select the current timezone offset in TIME use:
SELECT TIMEDIFF(NOW(), UTC_TIMESTAMP);
It will return: 02:00:00 if your timezone is +2:00 for that date
I made a cheatsheet here: Should MySQL have its timezone set to UTC?
To get Current timezone of the mysql you can do following things:
SELECT ##system_time_zone; # from this you can get the system timezone
SELECT IF(##session.time_zone = 'SYSTEM', ##system_time_zone, ##session.time_zone) # This will give you time zone if system timezone is different from global timezone
Now if you want to change the mysql timezone then:
SET GLOBAL time_zone = '+00:00'; # this will set mysql timezone in UTC
SET ##session.time_zone = "+00:00"; # by this you can chnage the timezone only for your particular session
If you need the GMT difference as an integer:
SELECT EXTRACT(HOUR FROM (TIMEDIFF(NOW(), UTC_TIMESTAMP))) AS `timezone`
To anyone come to find timezone of mysql db.
With this query you can get current timezone :
mysql> SELECT ##system_time_zone as tz;
+-------+
| tz |
+-------+
| CET |
+-------+
The command mention in the description returns "SYSTEM" which indicated it takes the timezone of the server. Which is not useful for our query.
Following query will help to understand the timezone
SELECT TIMEDIFF(NOW(), UTC_TIMESTAMP) as GMT_TIME_DIFF;
Above query will give you the time interval with respect to Coordinated Universal Time(UTC). So you can easily analyze the timezone. if the database time zone is IST the output will be 5:30
UTC_TIMESTAMP
In MySQL, the UTC_TIMESTAMP returns the current UTC date and time as a value in 'YYYY-MM-DD HH:MM:SS' or YYYYMMDDHHMMSS.uuuuuu format depending on the usage of the function i.e. in a string or numeric context.
NOW()
NOW() function. MySQL NOW() returns the value of current date and time in 'YYYY-MM-DD HH:MM:SS' format or YYYYMMDDHHMMSS.uuuuuu format depending on the context (numeric or string) of the function. CURRENT_TIMESTAMP, CURRENT_TIMESTAMP(), LOCALTIME, LOCALTIME(), LOCALTIMESTAMP, LOCALTIMESTAMP() are synonyms of NOW().
Check out MySQL Server Time Zone Support and the system_time_zone system variable. Does that help?
My PHP framework uses
SET LOCAL time_zone='Whatever'
on after connect, where 'Whatever' == date_default_timezone_get()
Not my solution, but this ensures SYSTEM timezone of MySQL server is always the same as PHP's one
So, yes, PHP is strongly envolved and can affect it
To get the current time according to your timezone, you can use the following (in my case its '+5:30')
select DATE_FORMAT(convert_tz(now(),##session.time_zone,'+05:30') ,'%Y-%m-%d')
You can try the following:
select sec_to_time(TIME_TO_SEC( curtime()) + 48000);
Here you can specify your time difference as seconds
Use LPAD(TIME_FORMAT(TIMEDIFF(NOW(), UTC_TIMESTAMP),’%H:%i’),6,’+') to get a value in MySQL's timezone format that you can conveniently use with CONVERT_TZ(). Note that the timezone offset you get is only valid at the moment in time where the expression is evaluated since the offset may change over time if you have daylight savings time. Yet the expression is useful together with NOW() to store the offset with the local time, which disambiguates what NOW() yields. (In DST timezones, NOW() jumps back one hour once a year, thus has some duplicate values for distinct points in time).
You just need to restart mysqld after altering timezone of System..
The Global time zone of MySQL takes timezone of System. When you change any such attribute of system, you just need a restart of Mysqld.
Insert a dummy record into one of your databases that has a timestamp
Select that record and get value of timestamp.
Delete that record. Gets for sure the timezone that the server is using to write data and ignores PHP timezones.
It may be
select timediff(current_time(),utc_time())
You won't get the timezone value directly this way.
##global.time_zone cannot be used as it is a variable, and it returns the value 'SYSTEM'.
If you need to use your query in a session with a changed timezone by using session SET TIME_ZONE =, then you will get that with ##session.time_zone. If you query ##global.time_zone, then you get 'SYSTEM'.
If you try datediff, date_sub, or timediff with now() and utc_time(), then you'll probably run into conversion issues.
But the things suggested above will probably work at least with some server versions. My version is 5.5.43-37 and is a hosted solution.
It is not a direct answer to this question but this blog post provides valuable information on the subject:
https://danuka-praneeth.medium.com/guide-to-time-zones-conversion-between-zones-and-storing-in-mysql-da4fc4350cd9.
Quote from the blog post:
In MySQL5+, TIMESTAMP values are converted from the session time zone
to UTC for storage, and from UTC to the session time zone for
retrieval. But DATETIME does not do any conversion.
Based on Timos answer.
Atleast on older version of mysql if your current timezone is lower than UTC then his solution returns NULL.
SELECT
IF(NOW() >= UTC_TIMESTAMP,
CONCAT('+', SUBSTRING_INDEX(TIMEDIFF(NOW(), UTC_TIMESTAMP), ':', 2)),
CONCAT('-', SUBSTRING_INDEX(TIMEDIFF(UTC_TIMESTAMP, NOW()), ':', 2))
) AS offset;
this returns (based on your timezone)
+02:00
-01:00
Try using the following code:
//ASP CLASSIC
Set dbdate = Server.CreateObject("ADODB.Recordset")
dbdate.ActiveConnection = MM_connection
dbdate.Source = "SELECT NOW() AS currentserverdate "
dbdate.Open()
currentdate = dbdate.Fields("currentserverdate").Value
response.Write("Server Time is "&currentdate)
dbdate.Close()
Set dbdate = Nothing