2021-04-11_LocalDate和LocalTime

2021-04-10  本文已影响0人  微笑碧落

0.前言

1. Java8引入的有关时间的api

2.LocalDate的创建方法(LocalTime类似)

public static LocalDate now()//
public static LocalDate of(int year, Month month, int dayOfMonth)//通过指定的时间创建一个LocalDate对象
//throws DateTimeParseException if the text cannot be parsed。通过字符串解析来获得LocalDate,如果不能解析就抛出如下异常。
public static LocalDate parse(CharSequence text)
public static LocalDate parse(CharSequence text, DateTimeFormatter formatter)

3.LocalDate的常用方法

3.1生成LocalDateTime

public LocalDateTime atStartOfDay(); //返回当天的起始时间
public LocalDateTime dateTime = localDate.atTime(16,25,30);//设置当前日期的时间

3.2获取年,月,日等

public int getYear();
public int getMonthValue();
public int getDayOfMonth();

3.3修改年,月,日等

public LocalDate withDayOfMonth(int dayOfMonth);
public LocalDate withDayOfYear(int dayOfYear); Returns a copy of this LocalDate with the day-of-year altered
public LocalDate withMonth(int dayOfMonth)
public LocalDate withYear(int dayOfMonth)

3.4返回一些特殊的日期

public LocalDate with(TemporalAdjuster adjuster)
localDate.with(TemporalAdjusters.firstDayOfMonth) //本月第一天
LocalDate.parse("2015-01-01").with(TemporalAdjusters.firstInMonth(DayOfWeek.MONDAY)); 

3.5日期计算( 前几天,后几天,前几个月等)

public LocalDate plusDays(long daysToAdd)
public LocalDate plusMonths(long monthsToAdd)
public LocalDate plusYears(long yearsToAdd)
public LocalDate plus(long amountToAdd, TemporalUnit unit)
如 localDate.plus(8, ChronoUnit.HOURS)
//其中 TemporalUnit的取值如下:
ChronoUnit.DAYS
WEEKS
MONTHS
YEARS
DECADES
CENTURIES
MILLENNIA
ERAS

3.6 日期比较

public boolean isBefore(ChronoLocalDate other);
public boolean isAfter(ChronoLocalDate other);

missionDate.isAfter(afterDatePicker.getValue().plusDays(-1)) ;
missionDate.isBefore(beforeDatePicker.getValue().plusDays(1));

4.格式化输出字符串

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMM");
String formatDate = LocalDate.now().format(formatter);

5.long转换为LocDateTime

LocalDateTime localDateTime = LocalDateTime.ofInstant(Instant.ofEpochMilli(millis), ZoneId.systemDefault());

参考文章

  1. localDateTime、date、localDate、string、long之间的转换处理
上一篇 下一篇

猜你喜欢

热点阅读