LocalDateTime时间操作使用

690 阅读3分钟

(1)在jdk8之前,一般使用的是Date操作时间,获取Date当前的时间戳为:

public static void main(String[] args) {
   Date date = new Date();
   System.out.println(date.getTime());
}

备注:Date中的getDate()等方法随着jdk升级也过时了;

(2)一般格式化Date使用的是SimpleDateFormat,代码为:

 static SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");

 public static void main(String[] args) {
   Date date = new Date();
   String time = simpleDateFormat.format(date);
   System.out.println(time);
 }
 

(3)SimpleDateFormat作为全局变量或者在多线程竞争下,是线程不安全的,

private static SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd    hh:mm:ss");

public static void main(String[] args) {
ExecutorService service = Executors.newFixedThreadPool(10);

for (int i = 0; i < 1_00_00; i++) {
   service.execute(() -> {
      System.out.println(dateStrFormat("2022-07-26 12:02:12"));
   });
  }
 service.shutdown();

}

public static Date dateStrFormat(String dateStr) {
  Date date = null;
  try {
    date = simpleDateFormat.parse(dateStr);
  } catch (ParseException e) {
     e.printStackTrace();
  }
  return date;
} 

会报错:

1658548504383.jpg (4)解决SimpleDateFormat线程安全问题,使用ThreadLocal,代码为:

private static ThreadLocal<SimpleDateFormat> simpleDateFormat = ThreadLocal.withInitial(()-> new SimpleDateFormat("yyyy-MM-dd hh:mm:ss"));

public static void main(String[] args) {
ExecutorService service = Executors.newFixedThreadPool(10);

for (int i = 0; i < 1_00_00; i++) {
 service.execute(() -> {
   System.out.println(dateStrFormat("2022-07-26 12:02:12"));
 });
}
service.shutdown();

}

public static Date dateStrFormat(String dateStr) {
Date date = null;
try {
 date = simpleDateFormat.get().parse(dateStr);
} catch (ParseException e) {
 e.printStackTrace();
}
return date;
}

(5) jdk8提供了LocalDateTime和LocalDate以及LocalTime操作时间,Date在不格式化的情况下,可读性很差,区别在于创建LocalDate 只获取某年某月,创建LocalTime只能获取时分秒,而LocalDateTime = LocalDate + LocalTime;

(6)LocalTime获取时间:

public static void main(String[] args) {
  LocalTime localTime = LocalTime.now();
  System.out.println(localTime);
}

(6)LocalDate获取时间:

public static void main(String[] args) {
  LocalDate localDate = LocalDate.now();
  System.out.println(localDate);
}

(7)LocalDate转时间戳:

public static void main(String[] args) {
  LocalDate localDate = LocalDate.now();
  long timestamp = localDate.atStartOfDay(ZoneOffset.ofHours(8)).toInstant().toEpochMilli();
  System.out.println(timestamp);

}

(8)时间戳转LocalDate:

public static void main(String[] args) {
  long timestamp = System.currentTimeMillis();
  LocalDate localDate = Instant.ofEpochMilli(timestamp).atZone(ZoneOffset.ofHours(8))
      .toLocalDate();
  System.out.println(localDate);
}

(9)LocalDateTime获取时间:

public static void main(String[] args) {
  LocalDateTime localDateTime = LocalDateTime.now();
  System.out.println(localDateTime);
}

(10)LocalDateTime转时间戳:

public static void main(String[] args) {
  LocalDateTime localDateTime = LocalDateTime.now();
  long timestamp = localDateTime.toInstant(ZoneOffset.ofHours(8)).toEpochMilli();
  System.out.println(timestamp);
}

(11)时间戳转LocalDateTime:

public static void main(String[] args) {
  long timestamp = System.currentTimeMillis();
  LocalDateTime localDateTime = Instant.ofEpochMilli(timestamp).atZone(ZoneOffset.ofHours(8))
      .toLocalDateTime();
  System.out.println(localDateTime);
}

(12)Date转LocalDateTime:

Date date = new Date();
System.out.println(date);
LocalDateTime localDateTime = date.toInstant().atZone(ZoneOffset.ofHours(8)).toLocalDateTime();
System.out.println(localDateTime);

(13)Date转LocalDate:

public static void main(String[] args) {
  Date date = new Date();
  System.out.println(date);
  LocalDate localDate = date.toInstant().atZone(ZoneOffset.ofHours(8)).toLocalDate();
  System.out.println(localDate);
}

(14)LocalDateTime转Date:

LocalDateTime localDateTime = LocalDateTime.now();
Date date = Date.from(localDateTime.atZone(ZoneOffset.ofHours(8)).toInstant());
System.out.println(date);

(15)LocalDateTime格式化时间:

public static void main(String[] args) {
  LocalDateTime now = LocalDateTime.now();
  DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
  String formatDateStr = now.format(dateTimeFormatter);
  System.out.println(formatDateStr);
}

(16)时间串转换为LocalDateTime:

public static void main(String[] args) {
  String time = "2022-07-23 13:44:31";
  DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
  LocalDateTime localDateTime = LocalDateTime.parse(time, dateTimeFormatter);
  System.out.println(localDateTime);
}

(17)LocalDate等提供很多方法操作,如:当前时间减一天:

public static void main(String[] args) {
  LocalDate localDate = LocalDate.now();
  LocalDate localDate1 = localDate.minusDays(1);
  System.out.println(localDate1);
}

(18)LocalDate计算时间差,代码如下:

LocalDate now1 = LocalDate.of(2022, 1, 1);
LocalDate now2 = LocalDate.of(2022, 2, 1);
Period period = Period.between(now1, now2);
System.out.println(period.getYears() + "-" + period.getMonths() + "-" + period.getDays());

(19)顺道一提,之前也有Calendar操作时间,代码如下:

public static void main(String[] args) {
  Calendar calendar = Calendar.getInstance();
  System.out.println(calendar);
  int year = calendar.get(Calendar.YEAR);
  System.out.println(year);
  int month = calendar.get(Calendar.MONTH) + 1;
  System.out.println(month);
  int days = calendar.get(Calendar.DAY_OF_YEAR);
  System.out.println(days);

}

(20)在解析中yyyy-MM-dd HH:mm:ss中yyyy和YYYY,以及HH和hh要注意一下,24小时制要用大写的HH,12小时的用hh,yyyy是Year,YYYY表示的是Week year,Week year 意思是当天所在的周属于的年份,一周从周日开始,周六结束,只要本周跨年,那么这周就算入下一年;

(21)总之,jdk8提供的LocalDateTime等都有很方便处理时间的方法,可以使用看看