推荐博客:https://www.jianshu.com/p/f4abe1e38e09
LocalDateTime currentTime = LocalDateTime.now();
LocalDate date1 = currentTime.toLocalDate();
Month month = currentTime.getMonth();
int day = currentTime.getDayOfMonth();
int seconds = currentTime.getSecond();
LocalDateTime date2 = currentTime.withDayOfMonth(10).withYear(2012);
//12 december 2014
LocalDate date3 = LocalDate.of(2014, Month.DECEMBER, 12);
//22 hour 15 minutes
LocalTime date4 = LocalTime.of(22, 15);
//parse a string
LocalTime date5 = LocalTime.parse("20:15:30");
// 1. 获取当前日期(年月日) -----打印输出-----2018-01-29
LocalDate localDate = LocalDate.now();
// 2. 根据年月日构建Date ----打印输出-----2018-01-30
LocalDate localDate1 = LocalDate.of(2018, 01, 30);
// 3. 字符串转换日期,默认按照yyyy-MM-dd格式,也可以自定义格式 -----打印输出-----2018-01-30
LocalDate localDate2 = LocalDate.parse("2018-01-30");
// 4. 获取本月第一天 -----打印输出-----2018-01-01
LocalDate firstDayOfMonth = localDate.with(TemporalAdjusters.firstDayOfMonth());
// 5. 获取本月第二天 -----打印输出-----2018-01-02
LocalDate secondDayOfMonth = localDate.withDayOfMonth(2);
// 6. 获取本月最后一天 -----打印输出-----2018-01-31
LocalDate lastDayOfMonth = localDate.with(TemporalAdjusters.lastDayOfMonth());
// 7. 明天 -----打印输出----- 2018-01-30
LocalDate tomorrowDay = localDate.plusDays(1L);
// 8. 昨天 -----打印输出----- 2018-01-28
LocalDate yesterday = localDate.minusDays(1L);
// 9. 获取本年第12天 -----打印输出----- 2018-04-30
LocalDate day = localDate.withDayOfYear(120);
// 10. 计算两个日期间的天数
long days = localDate.until(localDate1, ChronoUnit.DAYS);
// 11. 计算两个日期间的周数
long weeks = localDate.until(localDate1, ChronoUnit.WEEKS);
// 1. 获取当前时间,包含毫秒数 -----打印输出----- 21:03:26.315
LocalTime localTime = LocalTime.now();
// 2. 构建时间 -----打印输出----- 12:15:30
LocalTime localTime1 = LocalTime.of(12, 15, 30);
// 3. 获取当前时间,不包含毫秒数 -----打印输出----- 21:01:56
LocalTime localTime2 = localTime.withNano(0);
// 4. 字符串转为时间,还可以有其他格式,比如12:15, 12:15:23.233
// -----打印输出----- 12:15:30
LocalTime localTime3 = LocalTime.parse("12:15:30");
LocalDateTime默认的格式是 2018-01-29T21:23:26.774
这种格式,这可能与我们经常使用的格式不太符合,所以我们可以指定格式。
DateTimeFormatter本身提供了许多静态格式化常量,我们可以参考使用,如果不能满足我们的需求的话,我们可以自定义;
LocalDateTime的toString方法:
@Override
public String toString() {
return date.toString() + 'T' + time.toString();
}
// 1. 获取当前年月日 时分秒 -----打印输出----- 2018-01-29T21:23:26.774
LocalDateTime localDateTime = LocalDateTime.now();
// 2. 通过LocalDate和LocalTime构建 ----- 打印输出----- 2018-01-29T21:24:41.738
LocalDateTime localDateTime1 = LocalDateTime.of(LocalDate.now(), LocalTime.now());
// 3. 构建年月日 时分秒 -----打印输出----- 2018-01-29T19:23:13
LocalDateTime localDateTime2 = LocalDateTime.of(2018, 01, 29, 19, 23, 13);
// 4. 格式化当前时间 ----打印输出----- 2018/01/29
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy/MM/dd");
// 设置分钟数
LocalDateTime localDateTime = LocalDateTime.now().withMinute(23);
Java8,两个专门类引入来处理时间差。
Period
//Get the current date
LocalDate date1 = LocalDate.now();
//add 1 month to the current date
LocalDate date2 = date1.plus(1, ChronoUnit.MONTHS);
Period period = Period.between(date2, date1);
Duration
LocalTime time1 = LocalTime.now();
Duration twoHours = Duration.ofHours(2);
LocalTime time2 = time1.plus(twoHours);
Duration duration = Duration.between(time1, time2);
localDate1.until(localDate2, ChronoUnit.DAYS);
ChronoUnit.DAYS.between(localDate1, localDate2);
// 使用Duration,计算相差的秒,纳秒
// 注意:如果使用Duration计算,必须输入秒,如果没有秒,就会报错
LocalTime localTime1 = LocalTime.of(12, 12, 12);
LocalTime localTime2 = LocalTime.of(12, 13, 27);
Duration duration = Duration.between(localTime1, localTime2);
System.out.println(duration.getSeconds()); // 75
基本是基于Duration来实现的
//Get the current date
LocalDate today = LocalDate.now();
//add 1 week to the current date
LocalDate nextWeek = today.plus(1, ChronoUnit.WEEKS);
//add 1 month to the current date
LocalDate nextMonth = today.plus(1, ChronoUnit.MONTHS);
//add 1 year to the current date
LocalDate nextYear = today.plus(1, ChronoUnit.YEARS);
//add 10 years to the current date
LocalDate nextDecade = today.plus(1, ChronoUnit.DECADES);
ChronoUnit.SECONDS.between(LocalDateTime.now(), nextWeek);
有两种使用方式:
直接使用反射
Temporal#with(TemporalAdjuster) 【官方推荐使用,更加清晰】
//Get the current date
LocalDate date1 = LocalDate.now();
//get the next tuesday
LocalDate nextTuesday = date1.with(TemporalAdjusters.next(DayOfWeek.TUESDAY));
//get the second saturday of next month
LocalDate firstInYear = LocalDate.of(date1.getYear(),date1.getMonth(), 1);
LocalDate secondSaturday = firstInYear.with(
TemporalAdjusters.nextOrSame(DayOfWeek.SATURDAY)).with(
TemporalAdjusters.next(DayOfWeek.SATURDAY));
ZonedDateTime date1 = ZonedDateTime.parse("2007-12-03T10:15:30+05:30[Asia/Karachi]");
ZoneId id = ZoneId.of("Europe/Paris");
ZoneId currentZone = ZoneId.systemDefault();
时钟系统,用于查找当前时刻。通过指定一个时区,我们可以获取到当前的时刻,日期,时间。所以可以使用一个时钟来代替System.currenttimemillis()
和 TimeZone.getDefault()
。
在应用程序的最佳实践是将时钟传递给任何需要当前即刻的方法:
public class MyBean {
private Clock clock; // dependency inject
...
public void process(LocalDate eventDate) {
if (eventDate.isBefore(LocalDate.now(clock)) {
...
}
}
}
// 系统默认
Clock systemDefaultClock = Clock.systemDefaultZone();
System.out.println("Current DateTime with system default clock: " + LocalDateTime.now(systemDefaultClock));
System.out.println(systemDefaultClock.millis());
// 世界协调时UTC
Clock systemUTCClock = Clock.systemUTC();
System.out.println("Current DateTime with UTC clock: " + LocalDateTime.now(systemUTCClock));
System.out.println(systemUTCClock.millis());
//芝加哥
Clock clock = Clock.system(ZoneId.of(ZoneId.SHORT_IDS.get("CST")));
System.out.println("Current DateTime with CST clock: " + LocalDateTime.now(clock));
System.out.println(clock.millis());
并且我们可以使用 millis
方法来代替 System.currenttimemillis()
。
- Instant,表示的是时间戳,用于记录某一时刻的更改(JDK8之前的Timestamp);
- ZoneId 时区标志,比如用于标志欧洲/巴黎;
- ZoneOffset 时区偏移量,与UTC的偏移量;
- ZonedDateTime 与时区有关的日历系统,比如2007-12 03t10:15:30+01欧洲/巴黎;
- OffsetDateTime 用于与UTC偏移的日期时间,如如2007-12 03t10:15:30+01:00。
将Date转换为LocalDate,LocalTime,LocalDateTime可以借助于ZonedDateTime
和Instant
,实现如下:
Date date = new Date();
// current date: Fri Feb 02 16:43:13 CST 2018
System.out.println("current date: " + date);
// Date -> LocalDateTime
LocalDateTime localDateTime = date.toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime();
// localDateTime by Instant: 2018-02-02T16:43:13.073
System.out.println("localDateTime by Instant: " + localDateTime);
// Date -> LocalDate
LocalDate localDate = date.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
// localDateTime by ofInstant: 2018-02-02T16:43:13.073
System.out.println("localDate by Instant: " + localDate);
// Date -> LocalTime
LocalTime localTime = date.toInstant().atZone(ZoneId.systemDefault()).toLocalTime();
// localDate by Instant: 2018-02-02
System.out.println("localTime by Instant: " + localTime);
//2. Date -> LocalDateTime
localDateTime = LocalDateTime.ofInstant(date.toInstant(), ZoneId.systemDefault());
// localTime by Instant: 16:43:13.073
System.out.println("localDateTime by ofInstant: " + localDateTime);
LocalDateTime到Date的转换借助from
和toInstant
来实现。
LocalDateTime localDateTime = LocalDateTime.now();
// localDateTime: 2018-02-02T16:55:52.464
System.out.println("localDateTime: " + localDateTime);
// LocalDateTime -> Date
Date date = Date.from(localDateTime.atZone(ZoneId.systemDefault()).toInstant());
// LocalDateTime -> current date: Fri Feb 02 16:55:52 CST 2018
System.out.println("LocalDateTime -> current date: " + date);
// LocalDate -> Date,时间默认都是00
LocalDate localDate = LocalDate.now();
date = Date.from(localDate.atStartOfDay(ZoneId.systemDefault()).toInstant());
// LocalDate -> current date: Fri Feb 02 00:00:00 CST 2018
System.out.println("LocalDate -> current date: " + date);
单独的LocalTime转为Date没什么意义,所以如果LocalTime要转为Date,一般借助于LocalDate和LocalDateTime来实现就可以了。
字符串转日期
LocalDate localDate = LocalDate.parse("2018-09-09", DateTimeFormatter.ofPattern("yyyy-MM-dd"));
LocalDateTime localDateTime = LocalDateTime.parse("2018-09-10 12:12:12", DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
日期转字符串
String localDate = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
String localDateTime = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
// 也可以通过DateTimeFormatter的format方法
DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
localDateTime = dateTimeFormatter.format(LocalDateTime.now());
毫秒的话,是SSS,这个可能不经常使用,不过也要注意下:yyyy-MM-dd HH:mm:ss.SSS
时间戳与LocalDateTime转换
public static LocalDateTime convertToDate(long timestamp) {
// ofEpochSecond 以秒为单位, ofEpochMilli 以毫秒为单位
// Instant.ofEpochSecond(timestamp);
Instant instant = Instant.ofEpochMilli(timestamp);
return LocalDateTime.ofInstant(instant, ZoneId.systemDefault());
}
public static long convertToTimestamp() {
LocalDateTime localDateTime = LocalDateTime.now();
return localDateTime.atZone(ZoneId.systemDefault()).toInstant().toEpochMilli();
}