java常用日期操作大全
在最近的工作中遇到了一个新奇的事情,就是往数据库中存日期类型的数据,时分秒都是0。检查了数据库中的表字段是datetime,然后前端传的日期格式为:yyyy/MM/dd。最后时分秒由后台生成。比如传某个时间区间,前端传值为:2023/04/07---2023/04/08。我后台保存到数据库中的数据应该为:2023-04-07 00:00:00---2023/04/08 23:59:59。试了拼接,转换 最后存到表中的都是2023-04-07 00:00:00---2023/04/08 00:00:00。于是在网上看到一个hutool的时间工具类:DateUtil
例如我想获取当天的最后一秒:
public static void main(String[] args) { Date date = new Date(); System.out.println("DateUtil.endOfDay(date) = " + DateUtil.endOfDay(date)); }
输出结果为:
DateUtil.endOfDay(date) = 2023-04-07 23:59:59
获取当天最后的倒数第二秒(时间偏移)
public static void main(String[] args) { Date date = new Date(); System.out.println("DateUtil.offsetSecond(date,-2) = " + DateUtil.offsetSecond(DateUtil.endOfDay(date), -2)); }
输出结果为:
DateUtil.offsetSecond(date,-2) = 2023-04-07 23:59:57
除此之外 我们还可以对年 月 日 时 分 秒进行时间偏移
除了这些我们还可以获取昨天,明天,上周,下周,上个月和下个月的时间
//昨天 DateUtil.yesterday() //明天 DateUtil.tomorrow() //上周 DateUtil.lastWeek() //下周 DateUtil.nextWeek() //上个月 DateUtil.lastMonth() //下个月 DateUtil.nextMonth()
还可以计算两个日期之间的时间差,包括相差天数和相差小时等等
public static void main(String[] args) { String dateStr1 = "2023-04-07 11:12:13"; Date date1 = DateUtil.parse(dateStr1); String dateStr2 = "2023-04-09 11:12:13"; Date date2 = DateUtil.parse(dateStr2); //相差天数 long betweenDay = DateUtil.between(date1, date2, DateUnit.DAY); System.out.println("betweenDay = " + betweenDay); }
输出结果为:
betweenDay = 2
还可以字符串转日期
public static void main(String[] args) { String s = "2023-04-07"; Date date = DateUtil.parse(s,"yyyy-MM-dd"); System.out.println("date = " + date); }
输出结果为:
date = 2023-04-07 00:00:00
还可以对日期进行格式化输出
public static void main(String[] args) { String format = DateUtil.format(new Date(), "yyyy-MM-dd"); System.out.println("format = " + format); }
输出结果为:
format = 2023-04-07
如想了解其它日期类的操作,可参考hutool官方文档: