Java Date LocalDate LocalDateTime

61 篇文章 2 订阅
42 篇文章 2 订阅

Java Date LocalDate LocalDateTime

Java中常用时间类型 Date LocalDate LocalDateTime 在工作中使用很频繁,
但中间很多常用功能每次编写代码很繁琐,故而封装了以下三个工具类:

  • DateUtil 日期工具类
  • LocalDateUtil 新日期工具类
  • LocalDateTimeUtil 新日期工具类

用于日常使用。

Date 工具类

package cn.lihaozhe.util.date;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.temporal.TemporalAdjusters;
import java.util.Date;
import java.util.List;
import java.util.TimeZone;
import java.util.concurrent.ThreadLocalRandom;
import java.util.stream.Collectors;

/**
 * 日期工具类
 *
 * @author 李昊哲
 * @version 1.0
 */
public class DateUtil {

  /**
   * 默认时区
   */
  private final static String timeZone = "Asia/Shanghai";
  /**
   * 默认时区为东 8 区
   */
  private final static ZoneOffset zoneOffset = ZoneOffset.of("+8");

  /**
   * 默认时间字符串模板
   */
  private final static String pattern = "yyyy-MM-dd HH:mm:ss";

  /**
   * 获取当前系统日期
   *
   * @return 当前系统日期
   */
  public static Date date() {
    return new Date();
  }

  /**
   * 获取当前系统日期日期字符串
   *
   * @return 当前系统日期字符串
   */
  public static String now() {
    return format(new Date());
  }

  /**
   * 获取当前系统日期日期字符串
   *
   * @param pattern 日期格式化字符串模板
   * @return 当前系统日期字符串
   */
  public static String now(String pattern) {
    return format(new Date(), pattern);
  }


  /**
   * 日期对象格式化为字符串
   *
   * @param date Date对象
   * @return Date对象格式化后的日期字符串
   */
  public static String format(Date date) {
    return format(date, pattern);
  }

  /**
   * 日期对象格式化为字符串
   *
   * @param date    Date对象
   * @param pattern 日期格式化字符串模板
   * @return Date对象格式化后的日期字符串
   */
  public static String format(Date date, String pattern) {
    if (date == null) {
      return null;
    }
    SimpleDateFormat dateFormat = new SimpleDateFormat(pattern);
    return dateFormat.format(date);
  }

  /**
   * 日期对象格式化为字符串
   *
   * @param date     Date对象
   * @param pattern  日期格式化字符串模板
   * @param timeZone 时区
   * @return Date对象格式化后的日期字符串
   */
  public static String format(Date date, String pattern, String timeZone) {
    SimpleDateFormat dateFormat = new SimpleDateFormat(pattern);
    dateFormat.setTimeZone(TimeZone.getTimeZone(timeZone));
    return dateFormat.format(date);
  }

  /**
   * 获取根据时间毫秒数获取日期
   *
   * @param time 时间毫秒数
   * @return 日期
   */
  public static Date parse(long time) {
    return new Date(time);
  }

  /**
   * 将日期字符串解析为日期对象
   *
   * @param src 日期字符串
   * @return 日期字符串解析后日期对象
   * @throws ParseException 日期解析异常
   */
  public static Date parse(String src) throws ParseException {
    return parse(src, pattern);
  }

  /**
   * 将日期字符串解析为日期对象
   *
   * @param src     日期字符串
   * @param pattern 日期格式化字符串模板
   * @return 日期字符串解析后日期对象
   * @throws ParseException 日期解析异常
   */
  public static Date parse(String src, String pattern) throws ParseException {
    return new SimpleDateFormat(pattern).parse(src);
  }

  /**
   * 将日期字符串解析为日期对象
   *
   * @param src      日期字符串
   * @param pattern  日期格式化字符串模板
   * @param timeZone 时区
   * @return 日期字符串解析后日期对象
   * @throws ParseException 日期解析异常
   */
  public static Date parse(String src, String pattern, String timeZone) throws ParseException {
    SimpleDateFormat dateFormat = new SimpleDateFormat(pattern);
    dateFormat.setTimeZone(TimeZone.getTimeZone(timeZone));
    return dateFormat.parse(src);
  }

  /**
   * 获取系统当前日期时间毫秒数
   *
   * @return 当前时间毫秒数
   */
  public static long getTime() {
    return getTime(new Date());
  }

  /**
   * 获取日期时间毫秒数
   *
   * @param date 日期
   * @return 时间毫秒数
   */
  public static long getTime(Date date) {
    return date.getTime();
  }

  /**
   * 时间补零占位
   *
   * @param time 时间
   * @return 补零后的字符串
   */
  public static String zeroCompensation(int time) {
    if (time < 10) {
      return "0" + time;
    }
    return String.valueOf(time);
  }

  /**
   * 生成范围的随机时间,位于[start,end)范围内 时间倒序排列
   *
   * @param start 开始时间格式字符串
   * @param end   结束时间格式字符串
   * @param count 生成时间数量
   * @return 随机时间的集合
   */
  public static List<Date> random(String start, String end, int count) throws ParseException {
    return random(parse(start), parse(end), count);
  }

  /**
   * 生成范围的随机时间,位于[start,end)范围内 时间倒序排列
   *
   * @param start 开始时间
   * @param end   结束时间
   * @param count 生成时间数量
   * @return 随机时间的集合
   */
  public static List<Date> random(Date start, Date end, int count) {
    return ThreadLocalRandom.current()
        .longs(count, start.getTime(), end.getTime())
        .mapToObj(Date::new).sorted(Date::compareTo).collect(Collectors.toList());
  }

  /**
   * 生成范围的随机时间,位于[start,end)范围内 时间倒序排列
   *
   * @param start 开始时间
   * @param end   结束时间
   * @param count 生成时间数量
   * @return 随机时间的集合
   */
  public static List<LocalDate> random(LocalDate start, LocalDate end, int count) {
    List<Date> dateList = ThreadLocalRandom.current()
        .longs(count, LocalDateUtil.getMilliSeconds(start), LocalDateUtil.getMilliSeconds(end))
        .mapToObj(Date::new).sorted(Date::compareTo).toList();
    return dateList.stream().map(DateUtil::toLocalDate).collect(Collectors.toList());
  }

  /**
   * 生成范围的随机时间,位于[start,end)范围内 时间倒序排列
   *
   * @param start 开始时间
   * @param end   结束时间
   * @param count 生成时间数量
   * @return 随机时间的集合
   */
  public static List<LocalDateTime> random(LocalDateTime start, LocalDateTime end, int count) {
    List<Date> dateList = ThreadLocalRandom.current()
        .longs(count, LocalDateTimeUtil.getTime(start), LocalDateTimeUtil.getTime(end))
        .mapToObj(Date::new).sorted(Date::compareTo).toList();

    return dateList.stream().map(DateUtil::toLocalDateTime).collect(Collectors.toList());
  }

  /**
   * LocalDate 转 Date
   *
   * @param localDate LocalDate对象
   * @return Date对象
   */
  private static Date from(LocalDate localDate) {
    return from(localDate, zoneOffset);
  }

  /**
   * LocalDate 转 Date
   *
   * @param localDate LocalDate对象
   * @param zoneId    zoneId
   * @return Date对象
   */
  private static Date from(LocalDate localDate, String zoneId) {
    return from(localDate, ZoneOffset.of(zoneId));
  }

  /**
   * LocalDate 转 Date
   *
   * @param localDate  LocalDate对象
   * @param zoneOffset 时区
   * @return Date对象
   */

  private static Date from(LocalDate localDate, ZoneOffset zoneOffset) {
    return Date.from(localDate.atStartOfDay(zoneOffset).toInstant());
  }

  /**
   * LocalDateTime 转 Date
   *
   * @param localDateTime LocalDateTime对象
   * @return Date对象
   */
  private static Date from(LocalDateTime localDateTime) {
    return from(localDateTime, zoneOffset);
  }


  /**
   * LocalDateTime 转 Date
   *
   * @param localDateTime LocalDateTime
   * @param zoneId        zoneId
   * @return Date对象
   */
  private static Date from(LocalDateTime localDateTime, String zoneId) {
    return from(localDateTime, ZoneOffset.of(zoneId));
  }

  /**
   * LocalDateTime 转 Date
   *
   * @param localDateTime LocalDateTime对象
   * @param zoneOffset    时区
   * @return Date对象
   */

  private static Date from(LocalDateTime localDateTime, ZoneOffset zoneOffset) {
    return Date.from(localDateTime.toInstant(zoneOffset));
  }

  /**
   * Date 转 LocalDate
   *
   * @param date Date对象
   * @return LocalDateTime对象
   */
  public static LocalDate toLocalDate(Date date) {
    return toLocalDate(date, zoneOffset);
  }

  /**
   * Date 转 LocalDate
   *
   * @param date   Date对象
   * @param zoneId 时区ID
   * @return LocalDateTime对象
   */
  public static LocalDate toLocalDate(Date date, String zoneId) {
    return toLocalDate(date, ZoneOffset.of(zoneId));
  }

  /**
   * Date 转 LocalDate
   *
   * @param date       Date对象
   * @param zoneOffset 时区
   * @return LocalDate对象
   */
  public static LocalDate toLocalDate(Date date, ZoneOffset zoneOffset) {
    return date.toInstant().atOffset(zoneOffset).toLocalDate();
  }

  /**
   * Date 转 LocalDate
   *
   * @param date Date对象
   * @return Date对象
   */
  public static LocalDateTime toLocalDateTime(Date date) {
    return toLocalDateTime(date, zoneOffset);
  }


  /**
   * Date 转 LocalDate
   *
   * @param date   Date对象
   * @param zoneId 时区ID
   * @return LocalDateTime对象
   */
  public static LocalDateTime toLocalDateTime(Date date, String zoneId) {
    return toLocalDateTime(date, ZoneOffset.of(zoneId));
  }

  /**
   * Date 转 LocalDateTime
   *
   * @param date       Date对象
   * @param zoneOffset 时区
   * @return LocalDateTime对象
   */
  public static LocalDateTime toLocalDateTime(Date date, ZoneOffset zoneOffset) {
    return date.toInstant().atOffset(zoneOffset).toLocalDateTime();
  }

  /**
   * 获取某日期所在年份的第一天的日期
   *
   * @param date 日期
   * @return 所在年份的第一天的日期
   * @throws ParseException ParseException
   */
  public static Date firstDateOfYear(Date date) throws ParseException {
    return parse(format(date, "yyyy"), "yyyy");
  }

  /**
   * 获取某日期所在年份的最后一天的日期
   *
   * @param date 日期
   * @return 所在年份的最后一天的日期
   * @throws ParseException ParseException
   */
  public static Date lastDateOfYear(Date date) throws ParseException {
    return parse(format(date, "yyyy") + "-12-31 23:59:59", pattern);
  }

  /**
   * 获取某日期所在月份的第一天的日期
   *
   * @param date 日期
   * @return 所在月份的第一天的日期
   * @throws ParseException ParseException
   */
  public static Date firstDateOfMonth(Date date) throws ParseException {
    return parse(format(date, "yyyy-MM") + "-01", "yyyy-MM-dd");
  }

  /**
   * 获取某日期所在月份的最后一天的日期
   *
   * @param date 日期
   * @return 所在月份的最后一天的日期
   * @throws ParseException ParseException
   */
  public static Date lastDateOfMonth(Date date) throws ParseException {
    return from(toLocalDateTime(date).with(TemporalAdjusters.lastDayOfMonth()));
  }
}

LocalDate 工具类

package cn.lihaozhe.util.date;

import java.time.*;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.ThreadLocalRandom;

/**
 * LocalDate 工具类
 *
 * @author 李昊哲
 * @version 1.0
 */
public class LocalDateUtil {
  /**
   * 日期格式化模板字符串
   */
  private static final String formatter = "yyyy-MM-dd";

  /**
   * 默认时区为东 8 区
   */
  private final static ZoneOffset zoneOffset = ZoneOffset.of("+8");

  /**
   * 将LocalDate格式化为默认的日期格式字符串 例如:1983-11-22
   *
   * @param localDate 欲被格式化的日期
   * @return 根据日期格式字符串模板格式化的时间字符串
   */
  public static String format(LocalDate localDate) {
    return format(localDate, formatter);
  }

  /**
   * 将LocalDate格式化为指定的日期格式字符串
   *
   * @param localDate 欲被格式化的日期
   * @param formatter 日期字符串模板
   * @return 根据日期格式字符串模板格式化的时间字符串
   */
  public static String format(LocalDate localDate, String formatter) {
    if (localDate == null) {
      return null;
    }
    return DateTimeFormatter.ofPattern(formatter).format(localDate);
    // return localDate.format(DateTimeFormatter.ofPattern(formatter));
  }

  /**
   * 根据默认日期字符串模板将日期格式字符串解析为LocalDate
   * 默认日期字符串模板 yyyy-MM-dd
   *
   * @param text 日期格式字符串
   * @return LocalDate
   */
  public static LocalDate parse(String text) {
    return parse(text, formatter);
  }

  /**
   * 根据日期字符串模板将日期格式字符串解析为LocalDate
   *
   * @param text      日期格式字符串
   * @param formatter 日期格式字符串模板
   * @return LocalDate
   */
  public static LocalDate parse(String text, String formatter) {
    return LocalDate.parse(text, DateTimeFormatter.ofPattern(formatter));
  }

  /**
   * Date类型的时间转为LocalDateTime类型的时间
   *
   * @param date Date
   * @return LocalDate
   */
  public static LocalDate from(Date date) {
    return from(date, zoneOffset);
  }

  /**
   * Date类型的时间转为LocalDateTime类型的时间
   *
   * @param date   Date
   * @param zoneId 时区ID
   * @return LocalDate
   */
  public static LocalDate from(Date date, String zoneId) {
    return from(date, ZoneOffset.of(zoneId));
  }

  /**
   * Date类型的时间转为LocalDateTime类型的时间
   *
   * @param date Date
   * @param zone 时区
   * @return LocalDate
   */
  public static LocalDate from(Date date, ZoneId zone) {
    return date.toInstant().atZone(zone).toLocalDate();
  }

  /**
   * Date类型的时间转为LocalDateTime类型的时间
   *
   * @param date       Date
   * @param zoneOffset 时区
   * @return LocalDate
   */
  public static LocalDate from(Date date, ZoneOffset zoneOffset) {
    return date.toInstant().atOffset(zoneOffset).toLocalDate();
  }

  /**
   * LocalDate 转 Date
   *
   * @param localDate LocalDate对象
   * @return Date对象
   */
  public static Date toDate(LocalDate localDate) {
    return toDate(localDate, zoneOffset);
  }

  /**
   * LocalDate 转 Date
   *
   * @param localDate LocalDate对象
   * @param zoneId    zoneId
   * @return Date对象
   */
  public static Date toDate(LocalDate localDate, String zoneId) {
    return toDate(localDate, ZoneOffset.of(zoneId));
  }

  /**
   * LocalDate 转 Date
   *
   * @param localDate  LocalDate对象
   * @param zoneOffset 时区
   * @return Date对象
   */

  public static Date toDate(LocalDate localDate, ZoneOffset zoneOffset) {
    return Date.from(localDate.atStartOfDay(zoneOffset).toInstant());
  }

  /**
   * LocalDateTime 转 LocalDateTime
   *
   * @param localDate LocalDate对象
   * @return LocalDateTime对象
   */
  public static LocalDateTime toLocalDateTime(LocalDate localDate) {
    return toLocalDateTime(localDate, zoneOffset);
  }

  /**
   * LocalDateTime 转 LocalDateTime
   *
   * @param localDate LocalDate对象
   * @param zoneId    时区ID
   * @return LocalDateTime对象
   */
  public static LocalDateTime toLocalDateTime(LocalDate localDate, String zoneId) {
    return toLocalDateTime(localDate, ZoneOffset.of(zoneId));
  }

  /**
   * LocalDateTime 转 LocalDateTime
   *
   * @param localDate  LocalDate对象
   * @param zoneOffset 时区
   * @return LocalDateTime对象
   */
  public static LocalDateTime toLocalDateTime(LocalDate localDate, ZoneOffset zoneOffset) {
    return localDate.atStartOfDay(zoneOffset).toLocalDateTime();
  }

  /**
   * 获取时间毫秒数
   *
   * @return 时间毫秒数
   */
  public static long getMilliSeconds() {
    return getMilliSeconds(LocalDate.now());
  }

  /**
   * 获取时间毫秒数
   *
   * @param localDate LocalDate对象
   * @return 时间毫秒数
   */
  public static long getMilliSeconds(LocalDate localDate) {
    return getMilliSeconds(localDate, zoneOffset);
  }

  /**
   * 获取时间毫秒数
   *
   * @param localDate LocalDate对象
   * @param zoneId    时区ID
   * @return 时间毫秒数
   */
  public static long getMilliSeconds(LocalDate localDate, String zoneId) {
    return getMilliSeconds(localDate, ZoneOffset.of(zoneId));
  }

  /**
   * 获取时间毫秒数
   *
   * @param localDate  LocalDate对象
   * @param zoneOffset 时区
   * @return 时间毫秒数
   */
  public static long getMilliSeconds(LocalDate localDate, ZoneOffset zoneOffset) {
    return toLocalDateTime(localDate, zoneOffset).toInstant(zoneOffset).toEpochMilli();
  }

  /**
   * 时间毫秒数转LocalDate 使用系统默认时区
   *
   * @param milliSeconds 时间毫秒数
   * @return LocalDate
   */
  public static LocalDate parseMilliSeconds(Long milliSeconds) {
    return parseMilliSeconds(milliSeconds, ZoneId.systemDefault());
  }

  /**
   * 时间毫秒数转LocalDate
   *
   * @param milliSeconds 时间毫秒数
   * @param zoneId       时区
   * @return LocalDate
   */
  public static LocalDate parseMilliSeconds(Long milliSeconds, ZoneId zoneId) {
    return Instant.ofEpochMilli(milliSeconds).atZone(zoneId).toLocalDate();
  }

  /**
   * 随机生成 LocalDate 集合
   *
   * @param start 开始日期字符串 日期字符串格式 yyyy-MM-dd
   * @param end   结束日期字符串 日期字符串格式 yyyy-MM-dd
   * @param count 随机数量
   * @return LocalDate LocalDate集合
   */
  public static List<LocalDate> random(String start, String end, int count) {
    return random(start, end, count, formatter);
  }

  /**
   * 随机生成 LocalDate 集合
   *
   * @param start     开始日期字符串
   * @param end       结束日期字符串
   * @param count     随机数量
   * @param formatter 日期字符串模板
   * @return LocalDate LocalDate集合
   */
  public static List<LocalDate> random(String start, String end, int count, String formatter) {
    return random(parse(start, formatter), parse(end, formatter), count);
  }

  /**
   * 随机生成 LocalDate 集合
   *
   * @param start 开始日期
   * @param end   结束日期
   * @param count 随机数量
   * @return LocalDate LocalDate集合
   */
  public static List<LocalDate> random(LocalDate start, LocalDate end, int count) {
    List<LocalDate> list = new ArrayList<>();
    for (int i = 0; i < count; i++) {
      list.add(parseMilliSeconds(ThreadLocalRandom.current().nextLong(getMilliSeconds(start), getMilliSeconds(end))));
    }
    if (!list.isEmpty()) {
      list.sort(LocalDate::compareTo);
    }
    return list;
  }
}

LocalDateTime 工具类

package cn.lihaozhe.util.date;

import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.ThreadLocalRandom;


/**
 * LocalDateTime 工具类
 *
 * @author 李昊哲
 * @version 1.0
 */
public class LocalDateTimeUtil {
  /**
   * 时间格式化模板字符串
   */
  private static final String formatter = "yyyy-MM-dd HH:mm:ss";
  /**
   * 默认时区为东 8 区
   */
  private static final ZoneOffset zoneOffset = ZoneOffset.of("+8");

  /**
   * 将LocalDateTime格式化为时间指定的时间格式字符串
   *
   * @param localDateTime 欲被格式化的时间
   * @return 根据时间格式字符串模板格式化的时间字符串
   */
  public static String format(LocalDateTime localDateTime) {
    return format(localDateTime, formatter);
  }

  /**
   * 将LocalDateTime格式化为时间指定的时间格式字符串
   *
   * @param localDateTime 欲被格式化的时间
   * @param formatter     时间字符串模板
   * @return 根据时间格式字符串模板格式化的时间字符串
   */
  public static String format(LocalDateTime localDateTime, String formatter) {
    if (localDateTime == null) {
      return null;
    }
    return DateTimeFormatter.ofPattern(formatter).format(localDateTime);
    // return localDateTime.format(DateTimeFormatter.ofPattern(formatter));
  }

  /**
   * 根据时间字符串模板将时间格式字符串解析为LocalDateTime
   *
   * @param text 时间字符串
   * @return LocalDateTime
   */
  public static LocalDateTime parse(String text) {
    return parse(text, formatter);
  }

  /**
   * 根据时间字符串模板将时间格式字符串解析为LocalDateTime
   *
   * @param text      时间字符串
   * @param formatter 时间字符串模板
   * @return LocalDateTime
   */
  public static LocalDateTime parse(String text, String formatter) {
    return LocalDateTime.parse(text, DateTimeFormatter.ofPattern(formatter));
  }

  /**
   * Date类型的时间转为LocalDateTime类型的时间
   *
   * @param date Date
   * @return LocalDate
   */
  public static LocalDateTime from(Date date) {
    return from(date, zoneOffset);
  }

  /**
   * Date类型的时间转为LocalDateTime类型的时间
   *
   * @param date   Date
   * @param zoneId 时区ID
   * @return LocalDate
   */
  public static LocalDateTime from(Date date, String zoneId) {
    return from(date, ZoneOffset.of(zoneId));
  }

  /**
   * Date类型的时间转为LocalDateTime类型的时间
   *
   * @param date Date
   * @param zone 时区
   * @return LocalDate
   */
  public static LocalDateTime from(Date date, ZoneId zone) {
    return date.toInstant().atZone(zone).toLocalDateTime();
  }

  /**
   * Date类型的时间转为LocalDateTime类型的时间
   *
   * @param date       Date
   * @param zoneOffset 时区
   * @return LocalDateTime
   */
  public static LocalDateTime from(Date date, ZoneOffset zoneOffset) {
    return date.toInstant().atOffset(zoneOffset).toLocalDateTime();
  }

  /**
   * LocalDate 转 Date
   *
   * @param localDateTime LocalDateTime对象
   * @return Date对象
   */
  public static Date toDate(LocalDateTime localDateTime) {
    return toDate(localDateTime, zoneOffset);
  }

  /**
   * LocalDate 转 Date
   *
   * @param localDateTime LocalDateTime对象
   * @param zoneId        zoneId
   * @return Date对象
   */
  public static Date toDate(LocalDateTime localDateTime, String zoneId) {
    return toDate(localDateTime, ZoneOffset.of(zoneId));
  }

  /**
   * LocalDate 转 Date
   *
   * @param localDateTime LocalDateTime对象
   * @param zoneOffset    时区
   * @return Date对象
   */

  public static Date toDate(LocalDateTime localDateTime, ZoneOffset zoneOffset) {
    return Date.from(localDateTime.toInstant(zoneOffset));
  }

  /**
   * 获取当前时间毫秒数
   *
   * @return 当前时间毫秒数
   */
  public static long getTime() {
    return LocalDateTime.now(ZoneOffset.of("+8")).toInstant(ZoneOffset.of("+8")).toEpochMilli();
  }

  /**
   * 获取时间毫秒数
   *
   * @param localDateTime 日期时间
   * @return 当前时间毫秒数
   */
  public static long getTime(LocalDateTime localDateTime) {
    return localDateTime.toInstant(ZoneOffset.of("+8")).toEpochMilli();
  }

  /**
   * 时间毫秒数转LocalDateTime
   *
   * @param milliseconds 时间毫秒数
   * @return LocalDateTime
   */
  public static LocalDateTime parseMilliSeconds(Long milliseconds) {
    return LocalDateTime.ofInstant(Instant.ofEpochMilli(milliseconds), ZoneId.systemDefault());
  }

  /**
   * 时间毫秒数转LocalDateTime
   *
   * @param milliseconds 时间毫秒数
   * @param zoneId       ZoneId
   * @return LocalDateTime
   */
  public static LocalDateTime parseMilliSeconds(Long milliseconds, ZoneId zoneId) {
    return LocalDateTime.ofInstant(Instant.ofEpochMilli(milliseconds), zoneId);
  }

  /**
   * 随机生成 LocalDate 集合
   *
   * @param start 开始时间字符串 时间字符串格式 yyyy-MM-dd HH:mm:ss
   * @param end   结束时间字符串 时间字符串格式 yyyy-MM-dd HH:mm:ss
   * @param count 随机数量
   * @return LocalDateTime 集合
   */
  public static List<LocalDateTime> random(String start, String end, int count) {
    return random(start, end, count, formatter);
  }

  /**
   * 随机生成 LocalDateTime 集合
   *
   * @param start     开始时间字符串
   * @param end       结束时间字符串
   * @param count     随机数量
   * @param formatter 时间字符串模板
   * @return LocalDateTime LocalDateTime集合
   */
  public static List<LocalDateTime> random(String start, String end, int count, String formatter) {
    return random(parse(start, formatter), parse(end, formatter), count);
  }

  /**
   * 随机生成 LocalDateTime 集合
   *
   * @param start 开始时间
   * @param end   结束时间
   * @param count 随机数量
   * @return LocalDateTime 集合
   */
  public static List<LocalDateTime> random(LocalDateTime start, LocalDateTime end, int count) {
    List<LocalDateTime> list = new ArrayList<>();
    for (int i = 0; i < count; i++) {
      list.add(parseMilliSeconds(ThreadLocalRandom.current().nextLong(getTime(start), getTime(end))));
    }
    if (!list.isEmpty()) {
      list.sort(LocalDateTime::compareTo);
    }
    return list;
  }
}


  • 9
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
package com.aapoint.util; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; import java.time.temporal.TemporalAdjusters; public class LocalDateTimeUtil { /** * 比较 localDateTime2 是否在localDateTime1之前(比较大小) * @param localDateTime1 * @param localDateTime2 * @return */ public static Boolean compare(LocalDateTime localDateTime1,LocalDateTime localDateTime2){ return localDateTime1.isBefore(localDateTime2); } /** * 获取当前月份前/后的月份的第一天 * @param i 指定距离当前月份的时间 * @param state 状态 0.当月 1.前 2.后 * @return */ public static String firstDay(Integer state,Integer i){ LocalDateTime date = null; //type 类型 0.月 1.天 2.小时 3.分钟 4.秒 date = getLocalDateTime(state,0,i); //获取该月份的第一天 String firstDay = date.with(TemporalAdjusters.firstDayOfMonth()).format(DateTimeFormatter.ofPattern("yyyy-MM-dd")); // System.out.println("第一天为:"+firstDay); return firstDay; } /** * 获取当前月份前/后的月份的最后一天 * @param i 指定距离当前月份的时间 * @param state 状态 0.当月 1.前 2.后 * @return */ public static String lastDay(Integer state,Integer i){ LocalDateTime date = null; //type 类型 0.月 1.天 2.小时 3.分钟 4.秒 date = getLocalDateTime(state,0,i); //获取该月份的最后一天 String lastDay = date.with(TemporalAdjusters.lastDayOfMonth()).format(DateTimeFormatter.ofPattern("yyyy-MM-dd")); // System.out.println("最后一天为:"+lastDay); return lastDay; } /** * 获取当时间前/后的时间(天) * @param i 指定距离当前月份的时间 * @param state 状态 0.当月 1.前 2.后 * @return */ public static String obtainDay(Integer state,Integer i){ LocalDateTime date = null; //type 类型 0.月 1.天 2.小时 3.分钟 4.秒 date = getLocalDateTime(state,1,i); //获取天 String day = date.format(DateTimeFormatter.ofPattern("yyyy-MM-dd")); // System.out.println("获取的时间为(天):"+day); return day; } /** * 获取当时间前/后的时间(小时) * @param i 指定距离当前月份的时间 * @param state 状态 0.当月 1.前 2.后 * @return */ public static String obtainHours(Integer state,Integer i){ LocalDateTime date = null; //type 类型 0.月 1.天 2.小时 3.分钟 4.秒 date = getLocalDateTime(state,2,i); //获取该月份的最后一天 String hours = date.format(DateTimeFormatter.ofPattern("HH:mm:ss")); // System.out.println("获取的时间为(小时):"+hours); return hours; } /** * 获取当时间前/后的时间(小时) * @param i 指定距离当前月份的时间 * @param state 状态 0.当月 1.前 2.后 * @return */ public static String obtainMinutes(Integer state,Integer i){ LocalDateTime date = null; //type 类型 0.月 1.天 2.小时 3.分钟 4.秒 date = getLocalDateTime(state,3,i); //获取该月份的最后一天 String minutes = date.format(DateTimeFormatter.ofPattern("HH:mm:ss")); // System.out.println("获取的时间为(分钟):"+minutes); return minutes; } /** * 获取当时间前/后的时间(小时) * @param i 指定距离当前月份的时间 * @param state 状态 0.当月 1.前 2.后 * @return */ public static String obtainSeconds(Integer state,Integer i){ LocalDateTime date = null; //type 类型 0.月 1.天 2.小时 3.分钟 4.秒 date = getLocalDateTime(state,4,i); //获取该月份的最后一天 String seconds = date.format(DateTimeFormatter.ofPattern("HH:mm:ss")); // System.out.println("获取的时间为(秒):"+seconds); return seconds; } public static void main(String[] args) { System.out.println("当前时间为:"+LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"))); System.out.println("前一个月份的第一天为:"+LocalDateTimeUtil.firstDay(1,1)); System.out.println("前一个月份的最后一天为:"+LocalDateTimeUtil.lastDay(1,1)); System.out.println("当前时间的前一天为:"+LocalDateTimeUtil.obtainDay(1,1)); System.out.println("当前时间的后一天为:"+LocalDateTimeUtil.obtainDay(2,1)); System.out.println("当前时间的前一小时为:"+LocalDateTimeUtil.obtainHours(1,1)); System.out.println("当前时间的后一小时为:"+LocalDateTimeUtil.obtainHours(2,1)); System.out.println("当前时间的前一分钟为:"+LocalDateTimeUtil.obtainMinutes(1,1)); System.out.println("当前时间的后一分钟为:"+LocalDateTimeUtil.obtainMinutes(2,1)); System.out.println("当前时间的前一秒为:"+LocalDateTimeUtil.obtainSeconds(1,1)); System.out.println("当前时间的后一秒为:"+LocalDateTimeUtil.obtainSeconds(2,1)); } private static LocalDateTime getLocalDateTime(Integer state,Integer type,Integer i) { LocalDateTime date; if(state == 0){ date = LocalDateTime.now(); }else if(state == 1){ if(type == 0) { //获取月 date = LocalDateTime.now().minusMonths(i); }else if(type == 1){ //获取天 date = LocalDateTime.now().minusDays(i); }else if(type == 2){ //获取小时 date = LocalDateTime.now().minusHours(i); }else if(type == 3){ //获取分钟 date = LocalDateTime.now().minusMinutes(i);
`LocalDate` and `LocalDateTime` are classes in the Java API that represent date and time values without considering time zones. `LocalDate` represents a date (year, month, and day) without any specific time of day. It can be used to perform operations and calculations based on dates, such as checking if a date is before or after another, calculating the difference between two dates, or extracting specific components like the year or month. Here's an example of using `LocalDate`: ```java LocalDate currentDate = LocalDate.now(); System.out.println("Current date: " + currentDate); LocalDate specificDate = LocalDate.of(2022, 7, 1); System.out.println("Specific date: " + specificDate); boolean isBefore = specificDate.isBefore(currentDate); System.out.println("Is specific date before current date? " + isBefore); ``` `LocalDateTime` represents a date and time value without considering time zones. It includes the year, month, day, hour, minute, second, and nanosecond. It can be useful for scenarios where you need to work with both date and time information. Here's an example of using `LocalDateTime`: ```java LocalDateTime currentDateTime = LocalDateTime.now(); System.out.println("Current date and time: " + currentDateTime); LocalDateTime specificDateTime = LocalDateTime.of(2022, 7, 1, 12, 0); System.out.println("Specific date and time: " + specificDateTime); int hour = specificDateTime.getHour(); System.out.println("Hour of specific date and time: " + hour); ``` Both `LocalDate` and `LocalDateTime` are part of the `java.time` package introduced in Java 8. They provide a rich set of methods for manipulating and formatting date and time values in a localized manner.

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

李昊哲小课

桃李不言下自成蹊

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值