前言
项目里面 有这样的需求, 给你两个时间 10月1号 和10月20号。得出 1号到20号之间的 所有天。例如 1号,2号,3号,4号,…20号。
java没有原生的api,或者 是我没找到。 自己写了一个,觉得有些 意思 ,就发篇博客吧
直接上代码
/ * @param startTime 开始时间 * @param endTime 结束时间 * @param chronoUnit 时间刻度 note 当你传入的时间 是localTime 时候 ,时间刻度 就不能为Day * @return */ private static <T> T[] intervalTimesType(Temporal startTime, Temporal endTime, ChronoUnit chronoUnit) {
Objects.requireNonNull(startTime); Objects.requireNonNull(endTime); Objects.requireNonNull(chronoUnit); long interval = startTime.until(endTime, chronoUnit); //这里使用 linkList List<Temporal> result = new LinkedList<>(); for (int i = 0; i <= interval; i++) {
Temporal temp = startTime.plus(i, chronoUnit); result.add(temp); } return result.toArray((T[]) Array.newInstance(startTime.getClass(), 0)); } / * @param startTime 开始时间 * @param endTime 结束时间 * @param chronoUnit 时间刻度 * @return */ public static LocalDateTime[] intervalTimes(LocalDateTime startTime, LocalDateTime endTime, ChronoUnit chronoUnit) {
Objects.requireNonNull(startTime); Objects.requireNonNull(endTime); Objects.requireNonNull(chronoUnit); long interval = startTime.until(endTime, chronoUnit); //这里使用 linkList List<LocalDateTime> result = new LinkedList<>(); for (int i = 0; i <= interval; i++) {
LocalDateTime temp = startTime.plus(i, chronoUnit); result.add(temp); } return result.toArray(new LocalDateTime[]{
}); } / * @param startTime 开始时间 * @param endTime 结束时间 * @param chronoUnit 时间刻度 * @return */ public static LocalDate[] intervalTimes(LocalDate startTime, LocalDate endTime, ChronoUnit chronoUnit) {
Objects.requireNonNull(startTime); Objects.requireNonNull(endTime); Objects.requireNonNull(chronoUnit); long interval = startTime.until(endTime, chronoUnit); //这里使用 linkList List<LocalDate> result = new LinkedList<>(); for (int i = 0; i <= interval; i++) {
LocalDate temp = startTime.plus(i, chronoUnit); result.add(temp); } return result.toArray(new LocalDate[]{
}); }
讯享网
使用
讯享网 LocalDateTime now = LocalDateTime.now(); //提前四个小时 LocalDateTime beforeTime = now.minusHours(4); System.out.println("泛型》》》》》》"); LocalTime[] objects = intervalTimesType(beforeTime.toLocalTime(), now.toLocalTime(), ChronoUnit.HOURS); Arrays.asList(objects).forEach(System.out::println); beforeTime = now.minusDays(3); //localdate System.out.println("非泛型》》》》》》"); LocalDateTime[] intervalTimes = intervalTimes(beforeTime, now, ChronoUnit.DAYS); Arrays.asList(intervalTimes).forEach(System.out::println);
结果

讯享网
定义了 三个方法 ,第一个是泛型 比较推荐,后面两个都是指定类型的。随便用

如果有不懂的,可以关注我的公众号 “知我饭否” 向我留言。我会每天更新一些文章,有兴趣的可以 微信 搜索"知我饭否" or 扫描下方二维码

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容,请联系我们,一经查实,本站将立刻删除。
如需转载请保留出处:https://51itzy.com/kjqy/135746.html