简体   繁体   English

将时间戳转换为日期数据类型

[英]Convert timestamp to date data type

SELECT to_date(to_char(SYSTIMESTAMP, 'MM/DD/YYYY'), 'MM/DD/YYYY') FROM DUAL;

==> 04-MAR-16

Can anybody explain why this select statement doesn't result in '03/04/2016'? 任何人都可以解释为什么这个选择声明不会导致'03 / 04/2016'?

How can I write my selection so that it does result in this, as a date type? 作为日期类型,我如何编写我的选择以使其成为结果呢? I have also tried 我也试过了

SELECT to_date(to_char(trunc(SYSTIMESTAMP), 'MM/DD/YYYY'), 'MM/DD/YYYY') FROM DUAL

with the same result. 结果相同。

When a date is returned by a query and displayed, it obviously needs to be formatted in some way. 当查询返回日期并显示时,显然需要以某种方式格式化。 The way a date-type value is formatted is not determined by the query, but by the tool that executes your query and displays the result. 格式化日期类型值的方式不是由查询确定,而是由执行查询并显示结果的工具确定。

In the case of SQL developer you can set that format as follows: 对于SQL开发人员,您可以按如下方式设置该格式:

  1. Choose menu Tools > Preferences. 选择菜单工具>首选项。
  2. In the Preferences dialog, select Database > NLS from the left panel. 在“首选项”对话框中,从左侧面板中选择“数据库”>“NLS”。
  3. From the list of NLS parameters, enter "MM/DD/YYYY" 从NLS参数列表中,输入“MM / DD / YYYY”
  4. Save and close 保存并关闭

See also this question. 另见这个问题。

Note that to convert a timestamp to date you need just to truncate it: trunc(SYSTIMESTAMP) . 请注意,要将时间戳转换为日期,您只需截断它: trunc(SYSTIMESTAMP) Converting it to string and then back to a date is unnecessary. 将其转换为字符串然后返回日期是不必要的。

You are converting a datetime to a string and back to a date. 您正在将日期时间转换为字符串并返回日期。 Your system defaults the date format to DD-MMM-YY for output purposes; 为了输出目的,您的系统默认日期格式为DD-MMM-YY; this is the normal default for date in Oracle. 这是Oracle中日期的正常默认值。

It is important to understand that the internal data structure for date/time types has nothing to do with how they are presented. 重要的是要理解日期/时间类型的内部数据结构与它们的呈现方式无关。 So, if you want it in another format, convert to a string using to_char() . 因此,如果您想要其他格式,请使用to_char()转换为字符串。

If you want to change the default format, then look at NLS_DATE_FORMAT . 如果要更改默认格式,请查看NLS_DATE_FORMAT The documentation is here . 文档在这里

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

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