在多并发情况下使用SimpleDateFormat需格外注意 :SimpleDateFormat除了format是线程不安全以外,parse方法也是线程不安全的。
LocalDate
只获取年月日
LocalDate localDate = LocalDate.now(); //2020-06-01 LocalDate localDate1 = LocalDate.of(2020, 01, 01); //2020-01-01
获取年、月、日、星期几
int year = localDate.getYear(); //2020 int year1 = localDate.get(ChronoField.YEAR); //2020 Month month = localDate.getMonth(); //JUNE int month1 = localDate.get(ChronoField.MONTH_OF_YEAR); //6 int day = localDate.getDayOfMonth(); //1 int day1 = localDate.get(ChronoField.DAY_OF_MONTH); //1 DayOfWeek dayOfWeek = localDate.getDayOfWeek(); //MONDAY int dayOfWeek1 = localDate.get(ChronoField.DAY_OF_WEEK); //1
LocalTime
只获取时分秒
LocalTime localTime = LocalTime.of(23, 11, 11); //23:11:11 LocalTime localTime1 = LocalTime.now(); //23:15:51.710
获取时分秒
int hour = localTime.getHour(); //23 int hour1 = localTime.get(ChronoField.HOUR_OF_DAY); //23 int minute = localTime.getMinute(); //11 int minute1 = localTime.get(ChronoField.MINUTE_OF_HOUR); //11 int second = localTime.getSecond(); //11 int second1 = localTime.get(ChronoField.SECOND_OF_MINUTE); //11
LocalDateTime
LocalDateTime localDateTime = LocalDateTime.now(); //2020-06-01T23:23:50.559
Instant
获取秒数、获取毫秒数
Instant instant = Instant.now(); //2020-06-01T15:27:18.608Z long currentSecond = instant.getEpochSecond(); //1591025238 long currentMilli = instant.toEpochMilli(); //1591025238608
System.currentTimeMillis(); //1591025406619
修改
LocalDate localDate = LocalDate.of(2020, 01, 01); //2020-01-01 //增加一年 localDate = localDate .plusYears(1); //2021-01-01 localDate = localDate .plus(1, ChronoUnit.YEARS); //2022-01-01 //减少一年 localDate = localDate .minusYears(1); //2021-01-01 localDate = localDate .minus(1, ChronoUnit.YEARS); //2020-01-01 //增加一个月 localDate = localDate .plusMonths(1); //2020-02-01 localDate = localDate .plus(1, ChronoUnit.MONTHS); //2020-03-01 //减少一个月 localDate = localDate .minusMonths(1); //2020-02-01 localDate = localDate .minus(1, ChronoUnit.MONTHS); //2020-01-01 //加一天 localDate = localDate .plusDays(1); //2020-01-02 localDate = localDate .plus(1, ChronoUnit.DAYS); //2020-01-03 //减一天 localDate = localDate .minusDays(1); //2020-01-02 localDate = localDate .minus(1, ChronoUnit.DAYS); //2020-01-01
with修改年、月、日
//修改年为2030 localDate= localDate.withYear(2030 ); //2030-01-01 //修改年为2040 localDate= localDate.with(ChronoField.YEAR, 2040); //2040-01-01 //修改月为8 localDate= localDate.withMonth(2030 ); //2040-08-01 //修改月为9 localDate= localDate.with(ChronoField.MONTH_OF_YEAR, 9); //2040-09-01 //修改日为7 localDate= localDate.withDayOfMonth(7); //2040-09-07 //修改日为8 localDate= localDate.with(ChronoField.DAY_OF_MONTH, 8); //2040-09-08
格式化时间
LocalDate localDate = LocalDate.of(2019, 9, 10); //2019-09-10 String s1 = localDate.format(DateTimeFormatter.BASIC_ISO_DATE); //20190910 String s2 = localDate.format(DateTimeFormatter.ISO_LOCAL_DATE); //2019-09-10 //自定义格式化 DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("dd/MM/yyyy"); String s3 = localDate.format(dateTimeFormatter); //10/09/2019