简体   繁体   中英

Is there an ANSI/ISO SQL syntax to obtain the current time?

I would like to get a DB's current time, using Standard SQL. The result must either be in UTC or come with timezone information. Is that possible? If yes, how?


Apparently, there's CURRENT_TIMESTAMP, which is ANSI SQL, but is there an ANSI SQL syntax to retrieve just that? Some DBMS support select CURRENT_TIMESTAMP , others require select CURRENT_TIMESTAMP from DUAL . Any way to do this DBMS-independent?

Short answer:

There is no standard function to do this (as far as I know). Each vendor implemented their own functions to handle date and time, including retrieving the current time.

Possible solution (given you have control over the database):

You can create a view containing one record using (or a function proxying) the vendor specific function and use that as a source in your application.

For example (SQL Server)

CREATE VIEW dbo.[DateTime] AS
SELECT
  SYSUTCDATETIME() AS UTCDateTime
;

or in (MySQL)

CREATE VIEW DateTime AS
SELECT
  UTC_TIMESTAMP as UTCDateTime
;

The ANSI/ISO SQL standard has CURRENT_TIME to get time with timezone information, and LOCALTIME to get time without timezone information.

However, many products have their own functions instead.

Assuming you use SQL server:

SELECT CONVERT(varchar(10), GETUTCDATE(), 108)

The ANSI SQL way of doing this is to use the VALUES statement. This is similar to the SELECT statement, in that it returns a result set. But it doesn't reference any table. It's the standard way of doing something like what Oracle's DUAL pseudo-table is used for.

Here's a demo using MySQL 8.0:

mysql> VALUES ROW(CURRENT_TIMESTAMP);
+---------------------+
| column_0            |
+---------------------+
| 2021-11-22 14:56:58 |
+---------------------+

See:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM