java8 LocalData/Time

发布时间 2023-07-14 18:48:21作者: 方形固体移动工程师

ISO_DATE_TIMEL

String timeString = LocalDateTime.now().atOffset(ZoneOffset.ofHours(8)).format(DateTimeFormatter.ISO_DATE_TIME);
System.out.println(timeString);//2023-07-14T18:28:23.056+08:00

增加与减小

LocalDate date = LocalDate.now().minusMonths(1);
LocalDate date = LocalDate.now().minusMonths(1);
date.plusDays(0);

格式化

DateTimeFormatter tagetdf = DateTimeFormatter.ofPattern("yyyy-MM-dd");
tagetdf.format(date);//date LocalDate

时间戳转日期

System.out.println(System.currentTimeMillis());
Instant instant = Instant.ofEpochSecond(System.currentTimeMillis()/1000);
LocalDateTime now = LocalDateTime.ofInstant(instant, ZoneId.systemDefault());
System.out.println(now.getYear()+"-"+now.getMonthValue()+"-"+now.getDayOfMonth());

Instant longtime= Instant.ofEpochSecond(1682671618L);
LocalDateTime dateTime= LocalDateTime.ofInstant(longtime, ZoneId.systemDefault());
DateTimeFormatter tagetdf = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
String dateTimeStr = tagetdf.format(dateTime);
System.out.println(dateTimeStr);

字符串转时间

DateTimeFormatter sourcedf = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");
DateTimeFormatter tagetdf = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
LocalDateTime startTime = LocalDateTime.parse("2022-08-10 12:29", sourcedf);
LocalDateTime endTime = startTime.plusHours(24);
String tagetsstr = tagetdf.format(startTime);
String tagetestr = tagetdf.format(endTime);