Oracle to_char函数的使用

Oracle 版本

Oracle Database 10g Enterprise Edition Release 10.2.0.3.0 - Prod

使用场景

在oracle中存储的日期类型为Date.
精确到秒钟.
当存储的时间只精确到天时, 用String类型的java字段接收该值,会导致秒分时全部为0
例如 endtime字段为Date类型.

用java的String类型接收. 会自动把秒分时补为00:00:00

解决方案

使用to_char函数, 可以指定最终想要的日期格式的类型.
类似于java中的SimpleDateFormat.
例如在上面的例子中, 只想要查询出来的结果精确到天.那么在sql中使用如下

select 
    to_char(ENDTIME,'YYYY-MM-DD') ENDTIME 
        FROM tablename

使用的方法如上. 把要查询的字段传入to_char函数的第一个参数中.
第二个参数为指定日期的格式.
只需要查年月日,则指定为YYYY-MM-DD.
经过这样的sql处理后, 在java中用string 类型的接收.日期的格式如下.

### 其他时间的格式
在sql中 , yyyy-mm-dd hh24:mi:ss 中的字母, 大小写均可.
查询24小时格式的, 精确到秒的
select sysdate,to_char(sysdate,'yyyy-mm-dd hh24:mi:ss')from dual;
![](https://img-blog.csdnimg.cn/20181230144229747.png)
12小时格式的
select sysdate,to_char(sysdate,'yyyy-mm-dd hh:mi:ss')from dual;

参考文章
https://blog.csdn.net/dtjiawenwang88/article/details/73295181
https://blog.csdn.net/tanzongbiao/article/details/82528267

猜你喜欢

转载自www.cnblogs.com/jaythc/p/10199408.html