search
HomeDatabaseMysql TutorialORACLE单行函数与多行函数之四:日期函数示例

ORACLE单行函数与多行函数之四:日期函数示例

Jun 07, 2016 pm 03:50 PM
oraclefunctionMulti-lineexperimentdateenvironmentExample

实验环境 : BYS@bys1select * from nls_session_parameters where parameter='NLS_DATE_FORMAT'; PARAMETER VALUE -------------------- ------------------------------ NLS_DATE_FORMAT yyyy/mm/dd hh24:mi:ss BYS@bys1show parameter nls_lang NAME TYPE

实验环境

BYS@bys1>select * from nls_session_parameters where parameter='NLS_DATE_FORMAT';
PARAMETER            VALUE
-------------------- ------------------------------
NLS_DATE_FORMAT      yyyy/mm/dd hh24:mi:ss

BYS@bys1>show parameter nls_lang
NAME                                 TYPE        VALUE
------------------------------------ ----------- ------------------------------

nls_language                         string      AMERICAN


1.直接使用SYSDATE加减数字来操作日期

日期+或-1,都代表加减一天的时间;而如果是一小时或几分钟这种,可以用天/小时这种方法。

如下面语句,1小时是1/24;5分钟是1/24/12。86400:1天=24小时=24*60*60=86400秒

BYS@bys1>select sysdate+365,sysdate-1,sysdate-3,sysdate-1/24,sysdate-1/24/12 from dual;
SYSDATE+365         SYSDATE-1           SYSDATE-3           SYSDATE-1/24        SYSDATE-1/24/12
------------------- ------------------- ------------------- ------------------- -------------------

2014/11/02 19:26:15 2013/11/01 19:26:152013/10/30 19:26:15 2013/11/0218:26:15 2013/11/0219:21:15

2.TIMESTAMP 记录了年、月、日、时、分、秒和纳秒

SYSTIMESTAMP返回的是TIMESTAMP WITH TIME ZONE 类型的数据。+08:00表示当前是东八区。
BYS@bys1>select systimestamp from dual;
SYSTIMESTAMP
---------------------------------------------------------------------------
02-NOV-13 09.08.04.390741 PM +08:00
timestamp的显示格式不同于SYSDATE,要重新指定。
BYS@bys1>alter session set nls_timestamp_format='yyyy-mm-dd hh24:mi:ss.ff';
Session altered.

BYS@bys1>select systimestamp from dual;
SYSTIMESTAMP
---------------------------------------------------------------------------
02-NOV-13 09.11.19.258161 PM +08:00

表示TIMESTAMP的方法:
–to_timestamp('2013-02-09 23:59:59.000','yyyy-mm-dd hh24:mi:ss.ff')
–timestamp '2013-04-05 13:48:00.123456789'
–to_timestamp中的分隔符可以更换, timestamp中的日期分隔符必须是-,时间必须是:,秒后面必须跟上.
–timestamp可以精确表示到毫秒、微秒甚至纳秒级别
转换时未指定值时的默认值:年:同SYSDATE里的年;月:同SYSDATE里的月;日:1号;时分秒和纳秒:均为0
BYS@bys1>col a3 for a30
BYS@bys1>col a2 for a30
BYS@bys1>col a1 for a30
BYS@bys1>select to_timestamp('05 13','YY HH24') as a1,to_timestamp('05 13','mm mi') as a2,to_timestamp('05 13','dd ss') as a3 from dual;
A1                             A2                             A3
------------------------------ ------------------------------ ------------------------------
2005-11-01 13:00:00.000000000  2013-05-01 00:13:00.000000000  2013-11-05 00:00:13.000000000
关于微秒的指定方式:FF5表示给的时间戳可以有不超过5位的微秒。如果时间戳微秒有3位,指定转换为FF2,则报错。

同时在秒后最多只能指定9位。
BYS@bys1>select to_timestamp('05 13:48:22.778','DD HH24:MI:SS.FF5') from dual;
TO_TIMESTAMP('0513:48:22.778','DDHH24:MI:SS.FF5')
---------------------------------------------------------------------------
2013-11-05 13:48:22.778000000

要注意

BYS@bys1>select to_timestamp('05 13:48:22.778','DD HH24:MI:SS.FF2') from dual;
select to_timestamp('05 13:48:22.778','DD HH24:MI:SS.FF2') from dual
                    *
ERROR at line 1:
ORA-01880: the fractional seconds must be between 0 and 999999999

BYS@bys1>select to_timestamp('05 13:48:22.123456789','DD HH24:MI:SS.FF9') from dual;
TO_TIMESTAMP('0513:48:22.123456789','DDHH24:MI:SS.FF9')
---------------------------------------------------------------------------
2013-11-05 13:48:22.123456789
BYS@bys1>select to_timestamp('05 13:48:22.1234567890','DD HH24:MI:SS.FF9') from dual;
select to_timestamp('05 13:48:22.1234567890','DD HH24:MI:SS.FF9') from dual
                    *
ERROR at line 1:
ORA-01830: date format picture ends before converting entire input string
BYS@bys1>select to_timestamp('05 13:48:22.1234567890','DD HH24:MI:SS.FF10') from dual;
select to_timestamp('05 13:48:22.1234567890','DD HH24:MI:SS.FF10') from dual
                                             *
ERROR at line 1:
ORA-01821: date format not recognized

3.date函数只可以表示日期,不可以表示时间。在下面4中有应用示例。

默认值:年:同SYSDATE里的年;月:同SYSDATE里的月;日:1号;时分秒:均为0

4.判断指定日期是否是某一天的。to_date及date中如果只指定日期未指定时间,默认是0点0分0秒。即前一天23:59:59的下一秒。

注意BETWEEN AND 相当于大于等于和小于等于。所以属于某一天,严格来说应该是从当天0点的0秒到 当天23:59:59秒。1天除以86400即1秒

BYS@bys1> select 'TRUE' from dual where to_date('2013-11-02 21:48:22','YYYY-MM-DD HH24:MI:SS') between date'2013-11-01' and date'2013-11-06'-1/86400;

'TRU
----
TRUE

BYS@bys1>select 'TRUE' from dual where to_date('2013/11/02 21:45:43','YYYY-MM-DD HH24:MI:SS') between to_date('2013-11-02','yyyy-mm-dd') and  to_date('2013-11-03','yyyy-mm-dd hh24:mi:ss')-1/86400;

'TRU
----
TRUE
也可以用to_date对日期进行显式转换。
select 'TRUE' from dual where to_date('2013/11/02 21:45:43','YYYY-MM-DD HH24:MI:SS') between to_date('2013-11-02','yyyy-mm-dd') and  to_date('2013-11-03','yyyy-mm-dd hh24:mi:ss')-1/86400;
 
'TRUE'
------
TRUE

注意BETWEEN AND 相当于大于等于和小于等于

BYS@bys1> select 'TRUE' from dual where to_date('2013/11/02 21:45:43','YYYY-MM-DD HH24:MI:SS') >= date'2013-11-02' and to_date('2013/11/02 21:45:43','YYYY-MM-DD HH24:MI:SS') 'TRU
----
TRUE
其实也可以用小于11月3号来表示小于等于11月2号的23:59:59秒。

BYS@bys1> select 'TRUE' from dual where to_date('2013/11/02 23:59:59','YYYY-MM-DD HH24:MI:SS') >= date'2013-11-02' and to_date('2013/11/02 23:59:59','YYYY-MM-DD HH24:MI:SS') 'TRU
----
TRUE

5.MONTHS_BETWEEN(a,b):表示a和b两个日期的月份之差,是a-b,如果a日期比b晚,即比b大,则为正数;反之,为负数。

BYS@bys1>Select EMPNO,HIREDATE,MONTHS_BETWEEN(Sysdate,HIREDATE)/12 dday,sysdate From EMP where rownum      EMPNO HIREDATE                  DDAY SYSDATE
---------- ------------------- ---------- -------------------
      7369 1980/12/17 00:00:00 32.8784294 2013/11/02 18:37:05
      7499 1981/02/20 00:00:00 32.7036983 2013/11/02 18:37:05
BYS@bys1>select months_between(sysdate,to_date('2011/11/11 11:11:11','yyyy-mm-dd hh24:mi:ss')) as dday from dual;
      DDAY
----------
23.7196307
BYS@bys1>select months_between(to_date('2011/11/11 11:11:11','yyyy-mm-dd hh24:mi:ss'),sysdate) as dday from dual;
      DDAY
----------
-23.719639

6.ADD_MONTHS:表示给指定的日期加一个月数,即N个月后的日期。如果当前日期加上指定月数超过一年,则年份也自动增加。

BYS@bys1>select add_months(sysdate,1),add_months(sysdate,4) from dual;
ADD_MONTHS(SYSDATE, ADD_MONTHS(SYSDATE,
------------------- -------------------

2013/12/02 18:39:23 2014/03/02 18:39:23


7.NEXT_DAY:表示以当前时间为基准,下一个"目标日"的日期

BYS@bys1>select next_day(sysdate,'sunday'),next_day(sysdate,'tuesday') from dual;
NEXT_DAY(SYSDATE,'S NEXT_DAY(SYSDATE,'T
------------------- -------------------

2013/11/03 19:34:20 2013/11/05 19:34:20


8.LAST_DAY:计算当前日期的最后一天,即当月最后一天。

BYS@bys1>select last_day(sysdate) from dual;
LAST_DAY(SYSDATE)
-------------------

2013/11/30 18:43:16


9.使用ROUND:对日期进行四舍五入

只能对年、月、日、时、分进行四舍五入;不能操作秒。
BYS@bys1>select round(sysdate,'yy') as year,round(sysdate,'mm') as month,round(sysdate,'dd') as day,round(sysdate,'hh') as hour,round(sysdate,'hh24') as hour24,round(sysdate,'mi') as minutes  from dual;
YEAR                MONTH               DAY                 HOUR                HOUR24              MINUTES
------------------- ------------------- ------------------- ------------------- ------------------- -------------------
2014/01/01 00:00:00 2013/11/01 00:00:00 2013/11/03 00:00:00 2013/11/02 19:00:00 2013/11/02 19:00:00 2013/11/02 18:59:00
BYS@bys1> select round(sysdate,'ss') as sss from dual;
 select round(sysdate,'ss') as sss from dual
                      *
ERROR at line 1:

ORA-01899: bad precision specifier


10.使用TRUNC:对日期进行截取

BYS@bys1>set linesize 200
BYS@bys1>select trunc(sysdate,'yy') as year,trunc(sysdate,'mm') as month,trunc(sysdate,'dd') as day,trunc(sysdate,'hh') as hour,trunc(sysdate,'hh24') as hour24,trunc(sysdate,'mi') as minutes  from dual;
YEAR                MONTH               DAY                 HOUR                HOUR24              MINUTES
------------------- ------------------- ------------------- ------------------- ------------------- -------------------
2013/01/01 00:00:00 2013/11/01 00:00:00 2013/11/02 00:00:00 2013/11/02 18:00:00 2013/11/02 18:00:00 2013/11/02 18:52:00
只能截取年、月、日、时、分;不能截取秒。
BYS@bys1> select trunc(sysdate,'ss') as sss from dual;
 select trunc(sysdate,'ss') as sss from dual
                      *
ERROR at line 1:
ORA-01899: bad precision specifier
Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Explain the InnoDB Buffer Pool and its importance for performance.Explain the InnoDB Buffer Pool and its importance for performance.Apr 19, 2025 am 12:24 AM

InnoDBBufferPool reduces disk I/O by caching data and indexing pages, improving database performance. Its working principle includes: 1. Data reading: Read data from BufferPool; 2. Data writing: After modifying the data, write to BufferPool and refresh it to disk regularly; 3. Cache management: Use the LRU algorithm to manage cache pages; 4. Reading mechanism: Load adjacent data pages in advance. By sizing the BufferPool and using multiple instances, database performance can be optimized.

MySQL vs. Other Programming Languages: A ComparisonMySQL vs. Other Programming Languages: A ComparisonApr 19, 2025 am 12:22 AM

Compared with other programming languages, MySQL is mainly used to store and manage data, while other languages ​​such as Python, Java, and C are used for logical processing and application development. MySQL is known for its high performance, scalability and cross-platform support, suitable for data management needs, while other languages ​​have advantages in their respective fields such as data analytics, enterprise applications, and system programming.

Learning MySQL: A Step-by-Step Guide for New UsersLearning MySQL: A Step-by-Step Guide for New UsersApr 19, 2025 am 12:19 AM

MySQL is worth learning because it is a powerful open source database management system suitable for data storage, management and analysis. 1) MySQL is a relational database that uses SQL to operate data and is suitable for structured data management. 2) The SQL language is the key to interacting with MySQL and supports CRUD operations. 3) The working principle of MySQL includes client/server architecture, storage engine and query optimizer. 4) Basic usage includes creating databases and tables, and advanced usage involves joining tables using JOIN. 5) Common errors include syntax errors and permission issues, and debugging skills include checking syntax and using EXPLAIN commands. 6) Performance optimization involves the use of indexes, optimization of SQL statements and regular maintenance of databases.

MySQL: Essential Skills for Beginners to MasterMySQL: Essential Skills for Beginners to MasterApr 18, 2025 am 12:24 AM

MySQL is suitable for beginners to learn database skills. 1. Install MySQL server and client tools. 2. Understand basic SQL queries, such as SELECT. 3. Master data operations: create tables, insert, update, and delete data. 4. Learn advanced skills: subquery and window functions. 5. Debugging and optimization: Check syntax, use indexes, avoid SELECT*, and use LIMIT.

MySQL: Structured Data and Relational DatabasesMySQL: Structured Data and Relational DatabasesApr 18, 2025 am 12:22 AM

MySQL efficiently manages structured data through table structure and SQL query, and implements inter-table relationships through foreign keys. 1. Define the data format and type when creating a table. 2. Use foreign keys to establish relationships between tables. 3. Improve performance through indexing and query optimization. 4. Regularly backup and monitor databases to ensure data security and performance optimization.

MySQL: Key Features and Capabilities ExplainedMySQL: Key Features and Capabilities ExplainedApr 18, 2025 am 12:17 AM

MySQL is an open source relational database management system that is widely used in Web development. Its key features include: 1. Supports multiple storage engines, such as InnoDB and MyISAM, suitable for different scenarios; 2. Provides master-slave replication functions to facilitate load balancing and data backup; 3. Improve query efficiency through query optimization and index use.

The Purpose of SQL: Interacting with MySQL DatabasesThe Purpose of SQL: Interacting with MySQL DatabasesApr 18, 2025 am 12:12 AM

SQL is used to interact with MySQL database to realize data addition, deletion, modification, inspection and database design. 1) SQL performs data operations through SELECT, INSERT, UPDATE, DELETE statements; 2) Use CREATE, ALTER, DROP statements for database design and management; 3) Complex queries and data analysis are implemented through SQL to improve business decision-making efficiency.

MySQL for Beginners: Getting Started with Database ManagementMySQL for Beginners: Getting Started with Database ManagementApr 18, 2025 am 12:10 AM

The basic operations of MySQL include creating databases, tables, and using SQL to perform CRUD operations on data. 1. Create a database: CREATEDATABASEmy_first_db; 2. Create a table: CREATETABLEbooks(idINTAUTO_INCREMENTPRIMARYKEY, titleVARCHAR(100)NOTNULL, authorVARCHAR(100)NOTNULL, published_yearINT); 3. Insert data: INSERTINTObooks(title, author, published_year)VA

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.