最近小刘在Java的学习道路上遇到了一个问题:
oracle存储的inputTime是date型,但是不规范,是“2020-3-27 14:04:52”这种的。但是需求要求转成正常的“2020-03-27 14:04:52”。并且在这个时间的基础上往后生成一个月的时间。
在思索之下,我想到了两种办法:
- 1.直接SQL查询生成
select to_char(p.input_time + interval ‘1’ month,‘yyyy-MM-dd hh24:mm:ss’) inputTime from pre_info p
使用这种方法,可以直接通过SQL来生成一个月后的时间,同样的道理
interval '1’day ,interval '1’hour ,interval '1’year 对应 天、小时、年 - 2.通过Java代码生成
//这里bean定义的是date型
Date inputTime = queryPreStatus.getInpuTime();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Calendar calendar = Calendar.getInstance();
calendar.setTime(inputTime);
calendar.add(Calendar.MONTH,1);
Date time = calendar.getTime();
String oneMonthAfterTime = sdf.format(time);
最后生成的string型的时间,即是一个月后的时间,
如果需要跟当前时间比较,也可以生成当前时间后,使用compareto进行比较。
当然了,数据库资源珍贵的多,还是建议大家Java生成,节约资源