search
HomeDatabaseMysql TutorialOracle关于时间/日期的操作

Oracle关于时间/日期的操作

在oracle中有很多关于日期的函数,如:

  1、add_months()用于从一个日期值增加或减少一些月份

  date_value:=add_months(date_value,number_of_months)

  例:

  SQL> select add_months(sysdate,12) "Next Year" from dual;

  Next Year

  ----------

  13-11月-04

  SQL> select add_months(sysdate,112) "Last Year" from dual;

  Last Year

  ----------

  13-3月 -13

  SQL>

  2、current_date()返回当前会放时区中的当前日期

  date_value:=current_date

  SQL> column sessiontimezone for a15

  SQL> select sessiontimezone,current_date from dual;

  SESSIONTIMEZONE CURRENT_DA

  --------------- ----------

  +08:00 13-11月-03

  SQL> alter session set time_zone='-11:00'

  2 /

  会话已更改。

  SQL> select sessiontimezone,current_timestamp from dual;

  SESSIONTIMEZONE CURRENT_TIMESTAMP

  --------------- ------------------------------------

  -11:00 12-11月-03 04.59.13.668000 下午 -11:

  00

  SQL>

  3、current_timestamp()以timestamp with time zone数据类型返回当前会放时区中的当前日期

  timestamp_with_time_zone_value:=current_timestamp([timestamp_precision])

  SQL> column sessiontimezone for a15

  SQL> column current_timestamp format a36

  SQL> select sessiontimezone,current_timestamp from dual;

  SESSIONTIMEZONE CURRENT_TIMESTAMP

  --------------- ------------------------------------

  +08:00 13-11月-03 11.56.28.160000 上午 +08:

  00

  SQL> alter session set time_zone='-11:00'

  2 /

  会话已更改。

  SQL> select sessiontimezone,current_timestamp from dual;

  SESSIONTIMEZONE CURRENT_TIMESTAMP

  --------------- ------------------------------------

  -11:00 12-11月-03 04.58.00.243000 下午 -11:

  00

  SQL>

  4、dbtimezone()返回时区

  varchar_value:=dbtimezone

  SQL> select dbtimezone from dual;

  DBTIME

  ------

  -07:00

  SQL>

  5、extract()找出日期或间隔值的字段值

  date_value:=extract(date_field from [datetime_value|interval_value])

  SQL> select extract(month from sysdate) "This Month" from dual;

  This Month

  ----------

  11

  SQL> select extract(year from add_months(sysdate,36)) "3 Years Out" from dual;

  3 Years Out

  -----------

  2006

  SQL>

  6、last_day()返回包含了日期参数的月份的最后一天的日期

  date_value:=last_day(date_value)

  SQL> select last_day(date'2000-02-01') "Leap Yr?" from dual;

  Leap Yr?

  ----------

  29-2月 -00

  SQL> select last_day(sysdate) "Last day of this month" from dual;

  Last day o

  ----------

  30-11月-03

  SQL>

  7、localtimestamp()返回会话中的日期和时间

  timestamp_value:=localtimestamp

  SQL> column localtimestamp format a28

  SQL> select localtimestamp from dual;

  LOCALTIMESTAMP

  ----------------------------

  13-11月-03 12.09.15.433000

  下午

  SQL> select localtimestamp,current_timestamp from dual;

  LOCALTIMESTAMP CURRENT_TIMESTAMP

  ---------------------------- ------------------------------------

  13-11月-03 12.09.31.006000 13-11月-03 12.09.31.006000 下午 +08:

  下午 00

  SQL> alter session set time_zone='-11:00';

  会话已更改。

  SQL> select localtimestamp,to_char(sysdate,'DD-MM-YYYY HH:MI:SS AM') "SYSDATE" from dual;

  LOCALTIMESTAMP SYSDATE

  ---------------------------- ------------------------

  12-11月-03 05.11.31.259000 13-11-2003 12:11:31 下午

  下午

  SQL>

  8、months_between()判断两个日期之间的月份数量

  number_value:=months_between(date_value,date_value)

  SQL> select months_between(sysdate,date'1971-05-18') from dual;

  MONTHS_BETWEEN(SYSDATE,DATE'1971-05-18')

  ----------------------------------------

  389.855143

  SQL> select months_between(sysdate,date'2001-01-01') from dual;

  MONTHS_BETWEEN(SYSDATE,DATE'2001-01-01')

  ----------------------------------------

  34.4035409

  SQL>

  9、next_day()给定一个日期值,返回由第二个参数指出的日子第一次出现在的日期值(应返回相应日子的名称字符串)

  说明:

  单行日期函数

  单行日期函数操作data数据类型,绝大多数都有data数据类型的参数,绝大多数返回的也是data数据类型的值。

  10、add_months(,)

  返回日期d加上i个月后的结果。i可以使任意整数。如果i是一个小数,那么数据库将隐式的他转换成整数,将会截去小数点后面的部分。

  11、last_day()

  函数返回包含日期d的月份的最后一天

  12、months_between(,)

  返回d1和d2之间月的数目,如果d1和d2的日的日期都相同,或者都使该月的最后一天,那么将返回一个整数,否则会返回的结果将包含一个分数。

  13、new_time(,,)

  d1是一个日期数据类型,当时区tz1中的日期和时间是d时,返回时区tz2中的日期和时间。tz1和tz2时字符串。

  14、next_day(,)

  返回日期d后由dow给出的条件的第一天,dow使用当前会话中给出的语言指定了一周中的某一天,返回的时间分量与d的时间分量相同。

  select next_day(''01-jan-2000'',''monday'') "1st monday",next_day(''01-nov-2004'',''tuesday'')+7 "2nd tuesday") from dual;1st monday 2nd tuesday03-jan-2000 09-nov-2004

  15、round([,])

  将日期d按照fmt指定的格式舍入,fmt为字符串。

  16、syadate

  函数没有参数,返回当前日期和时间。

  17、trunc([,])

  返回由fmt指定的单位的日期d.

  单行转换函数

  单行转换函数用于操作多数据类型,在数据类型之间进行转换。

  18、chartorwid()

  c 使一个字符串,函数将c转换为rwid数据类型。

  select test_id from test_case where rowid=chartorwid(''aaaa0saacaaaaliaaa'')

  19、convert(,[,])

  c尾字符串,dset、sset是两个字符集,函数将字符串c由sset字符集转换为dset字符集,sset的缺省设置为数据库的字符集。

  20、hextoraw()

  x为16进制的字符串,函数将16进制的x转换为raw数据类型。

  21、rawtohex()

  x是raw数据类型字符串,函数将raw数据类转换为16进制的数据类型。

  22、rowidtochar()

  函数将rowid数据类型转换为char数据类型。

  23、to_char([[,)

  x是一个data或number数据类型,函数将x转换成fmt指定格式的char数据类型,如果x为日期nlsparm=nls_date_language 控制返回的月份和日份所使用的语言。如果x为数字nlsparm=nls_numeric_characters 用来指定小数位和千分位的分隔符,以及货币符号。

  nls_numeric_characters ="dg", nls_currency="string"

  24、to_date([,[,)

  c表示字符串,fmt表示一种特殊格式的字符串。返回按照fmt格式显示的c,nlsparm表示使用的语言。函数将字符串c转换成date数据类型。

  25、to_multi_byte()

  c表示一个字符串,函数将c的担子截字符转换成多字节字符。

  26、to_number([,[,)

  c表示字符串,fmt表示一个特殊格式的字符串,函数返回值按照fmt指定的格式显示。nlsparm表示语言,函数将返回c代表的数字。

  27、to_single_byte()

  将字符串c中得多字节字符转化成等价的单字节字符。该函数仅当数据库字符集同时包含单字节和多字节字符时才使用。

  1.日期时间间隔操作

  当前时间减去7分钟的时间

  select sysdate,sysdate - interval '7' MINUTE from dual

  当前时间减去7小时的时间

  select sysdate - interval '7' hour from dual

  当前时间减去7天的时间

  select sysdate - interval '7' day from dual

  当前时间减去7月的时间

  select sysdate,sysdate - interval '7' month from dual

  当前时间减去7年的时间

  select sysdate,sysdate - interval '7' year from dual

  时间间隔乘以一个数字

  select sysdate,sysdate - 8 *interval '2' hour from dual

  2.日期到字符操作

  select sysdate,to_char(sysdate,'yyyy-mm-dd hh24:mi:ss') from dual

  select sysdate,to_char(sysdate,'yyyy-mm-dd hh:mi:ss') from dual

  select sysdate,to_char(sysdate,'yyyy-ddd hh:mi:ss') from dual

  select sysdate,to_char(sysdate,'yyyy-mm iw-d hh:mi:ss') from dual

  参考oracle的相关关文档(ORACLE901DOC/SERVER.901/A90125/SQL_ELEMENTS4.HTM#48515)

  3. 字符到日期操作

  select to_date('2003-10-17 21:15:37','yyyy-mm-dd hh24:mi:ss') from dual

  具体用法和上面的to_char差不多。

  4. trunk/ ROUND函数的使用

  select trunc(sysdate ,'YEAR') from dual

  select trunc(sysdate ) from dual

  select to_char(trunc(sysdate ,'YYYY'),'YYYY') from dual

  5.oracle有毫秒级的数据类型

  --返回当前时间 年月日小时分秒毫秒

  select to_char(current_timestamp(5),'DD-MON-YYYY HH24:MI:SSxFF') from dual;

  --返回当前 时间的秒毫秒,可以指定秒后面的精度(最大=9)

  select to_char(current_timestamp(9),'MI:SSxFF') from dual;

  6.计算程序运行的时间(ms)

  declare

  type rc is ref cursor;

  l_rc rc;

  l_dummy all_objects.object_name%type;

  l_start number default dbms_utility.get_time;

  begin

  for I in 1 .. 1000

  loop

  open l_rc for

  'select object_name from all_objects '||

  'where object_id = ' || i;

  fetch l_rc into l_dummy;

  close l_rc;

  end loop;

  dbms_output.put_line

  ( round( (dbms_utility.get_time-l_start)/100, 2 ) ||

  ' seconds...' );

  end;

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
How to Grant Permissions to New MySQL UsersHow to Grant Permissions to New MySQL UsersMay 09, 2025 am 12:16 AM

TograntpermissionstonewMySQLusers,followthesesteps:1)AccessMySQLasauserwithsufficientprivileges,2)CreateanewuserwiththeCREATEUSERcommand,3)UsetheGRANTcommandtospecifypermissionslikeSELECT,INSERT,UPDATE,orALLPRIVILEGESonspecificdatabasesortables,and4)

How to Add Users in MySQL: A Step-by-Step GuideHow to Add Users in MySQL: A Step-by-Step GuideMay 09, 2025 am 12:14 AM

ToaddusersinMySQLeffectivelyandsecurely,followthesesteps:1)UsetheCREATEUSERstatementtoaddanewuser,specifyingthehostandastrongpassword.2)GrantnecessaryprivilegesusingtheGRANTstatement,adheringtotheprincipleofleastprivilege.3)Implementsecuritymeasuresl

MySQL: Adding a new user with complex permissionsMySQL: Adding a new user with complex permissionsMay 09, 2025 am 12:09 AM

ToaddanewuserwithcomplexpermissionsinMySQL,followthesesteps:1)CreatetheuserwithCREATEUSER'newuser'@'localhost'IDENTIFIEDBY'password';.2)Grantreadaccesstoalltablesin'mydatabase'withGRANTSELECTONmydatabase.TO'newuser'@'localhost';.3)Grantwriteaccessto'

MySQL: String Data Types and CollationsMySQL: String Data Types and CollationsMay 09, 2025 am 12:08 AM

The string data types in MySQL include CHAR, VARCHAR, BINARY, VARBINARY, BLOB, and TEXT. The collations determine the comparison and sorting of strings. 1.CHAR is suitable for fixed-length strings, VARCHAR is suitable for variable-length strings. 2.BINARY and VARBINARY are used for binary data, and BLOB and TEXT are used for large object data. 3. Sorting rules such as utf8mb4_unicode_ci ignores upper and lower case and is suitable for user names; utf8mb4_bin is case sensitive and is suitable for fields that require precise comparison.

MySQL: What length should I use for VARCHARs?MySQL: What length should I use for VARCHARs?May 09, 2025 am 12:06 AM

The best MySQLVARCHAR column length selection should be based on data analysis, consider future growth, evaluate performance impacts, and character set requirements. 1) Analyze the data to determine typical lengths; 2) Reserve future expansion space; 3) Pay attention to the impact of large lengths on performance; 4) Consider the impact of character sets on storage. Through these steps, the efficiency and scalability of the database can be optimized.

MySQL BLOB : are there any limits?MySQL BLOB : are there any limits?May 08, 2025 am 12:22 AM

MySQLBLOBshavelimits:TINYBLOB(255bytes),BLOB(65,535bytes),MEDIUMBLOB(16,777,215bytes),andLONGBLOB(4,294,967,295bytes).TouseBLOBseffectively:1)ConsiderperformanceimpactsandstorelargeBLOBsexternally;2)Managebackupsandreplicationcarefully;3)Usepathsinst

MySQL : What are the best tools to automate users creation?MySQL : What are the best tools to automate users creation?May 08, 2025 am 12:22 AM

The best tools and technologies for automating the creation of users in MySQL include: 1. MySQLWorkbench, suitable for small to medium-sized environments, easy to use but high resource consumption; 2. Ansible, suitable for multi-server environments, simple but steep learning curve; 3. Custom Python scripts, flexible but need to ensure script security; 4. Puppet and Chef, suitable for large-scale environments, complex but scalable. Scale, learning curve and integration needs should be considered when choosing.

MySQL: Can I search inside a blob?MySQL: Can I search inside a blob?May 08, 2025 am 12:20 AM

Yes,youcansearchinsideaBLOBinMySQLusingspecifictechniques.1)ConverttheBLOBtoaUTF-8stringwithCONVERTfunctionandsearchusingLIKE.2)ForcompressedBLOBs,useUNCOMPRESSbeforeconversion.3)Considerperformanceimpactsanddataencoding.4)Forcomplexdata,externalproc

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

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools