jdk1.8_时间类

java.time

LocalDate(年月日)

本地日期和时间

1. 最值

最大支持 +999999999-12-31 最小支持-999999999-01-01

2. 比较方法

equals

1
2
3
4
5
6
7
8
LocalDate today = LocalDate.now();
LocalDate tomorrow = today.plus(1, ChronoUnit.DAYS);
LocalDate yesterday = tomorrow.minusDays(2);
if(today.equals(tomorrow.minusDays(1))) {
System.out.println("true");
}else {
System.out.println("false");
}

3. now()方法

获取当前时间,无参时为当前系统默认时区,参数为时区id

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
/**
* Obtains the current date from the system clock in the specified time-zone.
* <p>
* This will query the {@link Clock#system(ZoneId) system clock} to obtain the current date.
* Specifying the time-zone avoids dependence on the default time-zone.
* <p>
* Using this method will prevent the ability to use an alternate clock for testing
* because the clock is hard-coded.
*
* @param zone the zone ID to use, not null
* @return the current date using the system clock, not null
*/
public static LocalDate now(ZoneId zone) {
return now(Clock.system(zone));
}
/**
* Obtains the current date from the system clock in the default time-zone.
* <p>
* This will query the {@link Clock#systemDefaultZone() system clock} in the default
* time-zone to obtain the current date.
* <p>
* Using this method will prevent the ability to use an alternate clock for testing
* because the clock is hard-coded.
*
* @return the current date using the system clock and default time-zone, not null
*/
public static LocalDate now() {
return now(Clock.systemDefaultZone());
}

4. plus()方法

public LocalDate plus(long amountToAdd, TemporalUnit unit) amountToAdd 要增加的总数 ;unit 时间单位 详见 ChronoUnit(TemporalUnit的实现类)

1
2
3
4
LocalDate today = LocalDate.now();
LocalDate tomorrow = today.plus(1, ChronoUnit.DAYS);

//plusYears(long yearsToAdd)\plusMonths(long monthsToAdd)\plusWeeks(long weeksToAdd)\plusDays(long daysToAdd)

5. minus()方法

public LocalDate minus(long amountToSubtract, TemporalUnit unit)

1
2
3
4
LocalDate today = LocalDate.now();
LocalDate tomorrow = today.minus(1, ChronoUnit.DAYS);

//minusYears(long yearsToSubtract)\minusMonths(long monthsToSubtract)\minusWeeks(long weeksToSubtract)\minusDays(long daysToSubtract)

6. of()方法、getDayOfWeek()方法

LocalDate of(int year, Month month, int dayOfMonth)/LocalDate of(int year, int month, int dayOfMonth)
LocalDate.getDayOfWeek() 判断传入日期是一周中的第几天 return DayOfWeek对象

1
2
3
4
LocalDate independenceDay = LocalDate.of(2014, Month.JULY, 4);
DayOfWeek dayOfWeek = independenceDay.getDayOfWeek();
System.out.println(dayOfWeek);//FRIDAY
System.out.println(dayOfWeek.getValue());//5

7. DateTimeFormatter

格式化时间,线程安全,类内创建一次可复用

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
//实例化 不指定时区
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");
//实例化 指定时区
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("E, yyyy-MMMM-dd HH:mm", Locale.US);

ZonedDateTime zdt = ZonedDateTime.now();
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm ZZZZ");
System.out.println(formatter.format(zdt));//2020-09-28T11:55 GMT+08:00

DateTimeFormatter zhFormatter = DateTimeFormatter.ofPattern("yyyy MMM dd EE HH:mm", Locale.CHINA);
System.out.println(zhFormatter.format(zdt));//2020 九月 28 星期一 11:55

DateTimeFormatter usFormatter = DateTimeFormatter.ofPattern("E, MMMM/dd/yyyy HH:mm", Locale.US);
System.out.println(usFormatter.format(zdt));//Mon, September/28/2020 11:55

System.out.println(DateTimeFormatter.ISO_DATE_TIME.format(zdt));//2020-09-28T11:55:39.209+08:00[Asia/Shanghai]

保留字母定义

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
* All letters 'A' to 'Z' and 'a' to 'z' are reserved as pattern letters. The
* following pattern letters are defined:
* <pre>
* Symbol Meaning Presentation Examples
* ------ ------- ------------ -------
* G era text AD; Anno Domini; A
* u year year 2004; 04
* y year-of-era year 2004; 04
* D day-of-year number 189
* M/L month-of-year number/text 7; 07; Jul; July; J
* d day-of-month number 10
*
* Q/q quarter-of-year number/text 3; 03; Q3; 3rd quarter
* Y week-based-year year 1996; 96
* w week-of-week-based-year number 27
* W week-of-month number 4
* E day-of-week text Tue; Tuesday; T
* e/c localized day-of-week number/text 2; 02; Tue; Tuesday; T
* F week-of-month number 3
*
* a am-pm-of-day text PM
* h clock-hour-of-am-pm (1-12) number 12
* K hour-of-am-pm (0-11) number 0
* k clock-hour-of-am-pm (1-24) number 0
*
* H hour-of-day (0-23) number 0
* m minute-of-hour number 30
* s second-of-minute number 55
* S fraction-of-second fraction 978
* A milli-of-day number 1234
* n nano-of-second number 987654321
* N nano-of-day number 1234000000
*
* V time-zone ID zone-id America/Los_Angeles; Z; -08:30
* z time-zone name zone-name Pacific Standard Time; PST
* O localized zone-offset offset-O GMT+8; GMT+08:00; UTC-08:00;
* X zone-offset 'Z' for zero offset-X Z; -08; -0830; -08:30; -083015; -08:30:15;
* x zone-offset offset-x +0000; -08; -0830; -08:30; -083015; -08:30:15;
* Z zone-offset offset-Z +0000; -0800; -08:00;
*
* p pad next pad modifier 1
*
* ' escape for text delimiter
* '' single quote literal '
* [ optional section start
* ] optional section end
* # reserved for future use
* { reserved for future use
* } reserved for future use

LocalDateTime(年月日时分秒)

本地日期和时间

1. 常用方法案例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
LocalDateTime ldt = LocalDateTime.of(2014, Month.DECEMBER, 31, 23, 59, 59);

DayOfWeek dayOfWeek = ldt.getDayOfWeek();
System.out.println(dayOfWeek); // WEDNESDAY

Month month = ldt.getMonth();
System.out.println(month); // DECEMBER

long minuteOfDay = ldt.getLong(ChronoField.MINUTE_OF_DAY);
System.out.println(minuteOfDay); // 23*60+59=1439

long dayOfWeekLong = ldt.getLong(ChronoField.DAY_OF_WEEK);
System.out.println(dayOfWeekLong); // 3

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

LocalDateTime parsed = LocalDateTime.parse("2016-12-01 23:59:59", formatter);
String string = parsed.format(formatter);
System.out.println(string); // 2016-12-01 23:59:59

2. Instant时间戳

在java.util.Date类与LocalDate、LocalDateTime类之间转换中 均可以通过Instant作为中间类完成转换

1
2
3
4
5
6
LocalDateTime ldt = LocalDateTime.of(2014, Month.DECEMBER, 31, 23, 59, 59);
//获取当前默认时区下ldt转换成的时间戳
Instant instant = ldt.atZone(ZoneId.systemDefault()).toInstant();

Date legacyDate = Date.from(instant);
System.out.println(legacyDate); // Wed Dec 31 23:59:59 CET 2014

LocalTime(时分秒)

本地日期和时间

1. Clock

1
2
3
4
5
6
7
8
Clock clock = Clock.systemDefaultZone();
//返回1970-01-01T00:00Z (UTC)至今的毫秒数,即按毫秒单位的unix时间戳
long t0 = clock.millis();
System.out.println(t0);

Instant instant = clock.instant();
Date legacyDate = Date.from(instant);
System.out.println(legacyDate);

2. ZoneId.getRules(),isBefore()

getRules 当前默认时区与指定时区间的转换公式
isBefore 当前时间是否在指定时间之前
ChronoUnit.between 按指定时间单位计算俩时间的差

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
ZoneId zone1 = ZoneId.of("Europe/Berlin");
ZoneId zone2 = ZoneId.of("Brazil/East");

System.out.println(zone1.getRules());//ZoneRules[currentStandardOffset=+01:00]
System.out.println(zone2.getRules());//ZoneRules[currentStandardOffset=-03:00]

// time
LocalTime now1 = LocalTime.now(zone1);//10:17:39.043
LocalTime now2 = LocalTime.now(zone2);//05:17:39.050

System.out.println(now1);
System.out.println(now2);

System.out.println(now1.isBefore(now2)); // false

long hoursBetween = ChronoUnit.HOURS.between(now1, now2);
long minutesBetween = ChronoUnit.MINUTES.between(now1, now2);
System.out.println(hoursBetween);//-4
System.out.println(minutesBetween);//-299


// create time

LocalTime now = LocalTime.now();
System.out.println(now);//16:17:39.052

LocalTime late = LocalTime.of(23, 59, 59);
System.out.println(late);//23:59:59
DateTimeFormatter germanFormatter =
DateTimeFormatter
.ofLocalizedTime(FormatStyle.SHORT)
.withLocale(Locale.GERMAN);

LocalTime formateTime = LocalTime.parse("13:37", germanFormatter);
System.out.println(formateTime);//13:37

ZonedDateTime

带时区的日期和时间(ISO-8601)

1
2
ZonedDateTime  zonedDateTime = ZonedDateTime.now();
System.out.println(zonedDateTime);//2020-09-28T17:19:44.836+08:00[Asia/Shanghai]
Donate
  • Copyright: Copyright is owned by the author. For commercial reprints, please contact the author for authorization. For non-commercial reprints, please indicate the source.
  • Copyrights © 2020 李明华
  • Visitors: | Views:

请我喝杯咖啡吧~

支付宝
微信