本示例演示如何使用该DateUtils.round()方法获取日期的最近的小时,分钟和秒。
package org.nhooo.example.commons.lang; import org.apache.commons.lang3.time.DateFormatUtils; import org.apache.commons.lang3.time.DateUtils; import org.apache.commons.lang3.time.FastDateFormat; import java.util.Calendar; import java.util.Date; public class DateRoundingDemo { public static void main(String[] args) { FastDateFormat formatter = DateFormatUtils.ISO_8601_EXTENDED_DATETIME_TIME_ZONE_FORMAT; Date now = new Date(); System.out.println("now = " + formatter.format(now)); // 获得最近的秒 Date nearestSecond = DateUtils.round(now, Calendar.SECOND); System.out.println("nearestSecond = " + formatter.format(nearestSecond)); // 取得最近的分钟 Date nearestMinute = DateUtils.round(now, Calendar.MINUTE); System.out.println("nearestMinute = " + formatter.format(nearestMinute)); // 取得最近的时间 Date nearestHour = DateUtils.round(now, Calendar.HOUR); System.out.println("nearestHour = " + formatter.format(nearestHour)); } }
程序结果如下:
now = 2019-07-24T10:29:21+08:00 nearestSecond = 2019-07-24T10:29:22+08:00 nearestMinute = 2019-07-24T10:29:00+08:00 nearestHour = 2019-07-24T10:00:00+08:00
Maven依赖
<!-- https://search.maven.org/remotecontent?filepath=org/apache/commons/commons-lang3/3.9/commons-lang3-3.9.jar --> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-lang3</artifactId> <version>3.9</version> </dependency>