简体   繁体   English

Oracle:如何将字符串转换为日期格式

[英]Oracle: How to convert a string into date format

Have done a lot of search before asking this question, like How to convert a string into date format , How to convert a string into date , but still can't figure it out. 在问这个问题之前做了很多搜索,例如如何将字符串转换为日期格式如何将字符串转换为日期 ,但仍然无法弄清楚。

So, here's the question, how to convert these string dates into date in Oracle : 因此,这是一个问题,如何在Oracle中将这些字符串日期转换为日期:

"2016-08-15 10:45:30" (String type) -> 20160815 (Date type) “ 2016-08-15 10:45:30”(字符串类型)-> 20160815(日期类型)

"20160815104530" (String type) -> 20160815 (Date type) “ 20160815104530”(字符串类型)-> 20160815(日期类型)

Any idea will be appreciated. 任何想法将不胜感激。

You use to_date() : 您使用to_date()

select to_date(substr(str1, 1, 10), 'YYYY-MM-DD')
select to_date(substr(str2, 1, 8), 'YYYYMMDD')

You are mixing two things here: 您在这里混合两件事:

The first is the conversion of a String data type, in Oracle VARCHAR2 into a DATE data type. 首先是将Oracle VARCHAR2中的String数据类型转换为DATE数据类型。 The DATE data type has a precision of seconds, you can't change that. DATE数据类型的精度为秒,您无法更改。 A DATE data type will always give you the date and time component, ie year, month, day, hours, minutes and seconds: Oracle SQL Data Type Documentation DATE数据类型将始终为您提供日期和时间部分,即年,月,日,小时,分钟和秒: Oracle SQL数据类型文档

However, the second part of what you are asking is about how to format the date when retrieved. 但是,您要询问的第二部分是有关如何在检索时格式化日期。 This is helpful when running reports, or other kinds of visual display of dates. 在运行报告或日期的其他可视显示方式时,这很有用。 For example, in the US you would most likely want your date columns appear in the format MM/DD/YYYY while everywhere else in the world you most likely want to stick with DD/MM/YYYY . 例如,在美国,您很可能希望日期列以MM/DD/YYYY格式显示,而在世界上其他任何地方,您都希望使用DD/MM/YYYY Oracle lets you do that by telling it what NLS_DATE_FORMAT you want to use. Oracle通过告诉您要使用的NLS_DATE_FORMAT来做到这一点。 You can set that parameter for each individual session as well as on database level, it is up to you (and your DBA) to decide where and when you want to set that. 您可以为每个单独的会话以及在数据库级别上设置该参数,这取决于您(和您的DBA)决定在哪里以及何时进行设置。 In your case you can apply this via the ALTER SESSION command: 您可以通过ALTER SESSION命令来应用它:

SQL> ALTER SESSION SET nls_date_format='YYYY-MM-DD';

Session altered.

SQL> SELECT TO_DATE('2016-08-15 10:45:30', 'YYYY-MM-DD HH24:MI:SS') FROM DUAL;

TO_DATE(
----------
2016-08-15

SQL> SELECT TO_DATE('20160815104530', 'YYYYMMDDHH24MISS') FROM DUAL;

TO_DATE(
----------
2016-08-15

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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