Java8新特性六:New Date-Time API | Java提升营

Java8新特性六:New Date-Time API

Java 8中引入了新的Date-Time API,解决了旧的日期时间API的以下缺点:

  • 线程不安全问题:旧的 java.util.Date 是线程不安全的,而 新的 Date-Time API 是不可变的且没有提供setter方法
  • 操作单调:旧API仅提供了少量的方法去操作时间,而新的API提供了许多日期操作

Java 8在java.time包下引入了新的Date-Time API,其中最重要的类是:

  • Local :简化版的Date-Time API,没有时区处理的复杂性。
  • Zoned :专门用于处理各种时区的Date-Time API。
  1. LocalDate / LocatTimeLocalDateTime
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
50
51
52
53
54
// Java code for LocalDate 
// / LocalTime Function
import java.time.*;
import java.time.format.DateTimeFormatter;

public class Date {

public static void LocalDateTimeApi()
{

// the current date
LocalDate date = LocalDate.now();
System.out.println("the current date is "+ date);


// the current time
LocalTime time = LocalTime.now();
System.out.println("the current time is "+ time);


// will give us the current time and date
LocalDateTime current = LocalDateTime.now();
System.out.println("current date and time : "+ current);


// to print in a particular format
DateTimeFormatter format = DateTimeFormatter.ofPattern("dd-MM-yyyy HH:mm:ss");

String formatedDateTime = current.format(format);

System.out.println("in foramatted manner "+ formatedDateTime);

// printing months days and seconds
Month month = current.getMonth();
int day = current.getDayOfMonth();
int seconds = current.getSecond();
System.out.println("Month : "+month+" day : "+ day+" seconds : "+seconds);

// printing some specified date
LocalDate date2 = LocalDate.of(1950,1,26);
System.out.println("the repulic day :"+date2);

// printing date with current time.
LocalDateTime specificDate = current.withDayOfMonth(24).withYear(2016);

System.out.println("specfic date with current time : "+specificDate);
}

// Driver code
public static void main(String[] args)
{
LocalDateTimeApi();
}
}

输出:

1
2
3
4
5
6
7
the current date is 2020-04-09
the current time is 06:21:10.409
current date and time : 2020-04-09T06:21:10.410
in foramatted manner 09-04-2020 06:21:10
Month : APRIL day : 9 seconds : 10
the repulic day :1950-01-26
specfic date with current time : 2016-04-24T06:21:10.410
  1. Zoned date-time API
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
50
51
52
// Java code for Zoned date-time API 
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;

public class Zone {

// Function to get Zoned Date and Time
public static void ZonedTimeAndDate() {
LocalDateTime date = LocalDateTime.now();
DateTimeFormatter format1 = DateTimeFormatter.ofPattern("dd-MM-yyyy HH:mm:ss");

String formattedCurrentDate = date.format(format1);

System.out.println("formatted current Date and Time : "+formattedCurrentDate);

OffsetDateTime dateTime = OffsetDateTime.now();

System.out.println("formatted current Date Time : "+ dateTime.format(format1));

// to get the current zone
ZonedDateTime currentZone = ZonedDateTime.now();
System.out.println("the current zone is "+ currentZone.getZone());

// getting time zone of specific place
// we use withZoneSameInstant(): it is
// used to return a copy of this date-time
// with a different time-zone,
// retaining the instant.
ZoneId tokyo = ZoneId.of("Asia/Tokyo");

ZonedDateTime tokyoZone = currentZone.withZoneSameInstant(tokyo);

System.out.println("tokyo time zone is " + tokyoZone);

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

String formatedDateTime = tokyoZone.format(format);

System.out.println("formatted tokyo time zone "+ formatedDateTime);

}

// Driver code
public static void main(String[] args)
{

ZonedTimeAndDate();

}
}

输出:

1
2
3
4
5
formatted current Date and Time : 09-04-2020 06:21:13
formatted current Date Time : 09-04-2020 06:21:13
the current zone is Etc/UTC
tokyo time zone is 2020-04-09T15:21:13.220+09:00[Asia/Tokyo]
formatted tokyo time zone 09-04-2020 15:21:13
  1. PeriodDuration
  • Period:表示一段时间的年、月、日,并使用between()方法获取两个日期之间的差作为Period 对象返回
1
2
3
4
LocalDate startDate = LocalDate.of(2018, 2, 20);
LocalDate endDate = LocalDate.of(2020, 1, 15);

Period period = Period.between(startDate, endDate);

可以从Period对象中获取日期单元,使用getYears()getMonhs()getDays()方法。

还可以通过Period的isNegative()来判断日期的大小。

  • Duration:表示秒或纳秒时间间隔,适合处理较短的时间,需要更高的精确性。我们能使用between()方法比较两个瞬间的差
1
2
3
4
Instant start = Instant.parse("2020-04-03T10:15:30.00Z");
Instant end = Instant.parse("2020-04-03T10:16:30.00Z");

Duration duration = Duration.between(start, end);

那么我们能使用getSeconds() 或 getNanoseconds() 方法获取时间单元的值

1
2
duration.getSeconds();
duration.getNanoseconds();
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
// Java code for period and duration 
import java.time.LocalDate;
import java.time.LocalTime;
import java.time.Month;
import java.time.Duration;
import java.time.Period;

public class Geekforgeeks {

public static void checkingPeriod() {
LocalDate date1 = LocalDate.now();

LocalDate date2 = LocalDate.of(2014, Month.DECEMBER, 12);

Period gap = Period.between(date2, date1);
System.out.println("gap between dates is a period of "+gap);
}

// Function to check duration
public static void checkingDuraion() {

LocalTime time1 = LocalTime.now();
System.out.println("the current time is " + time1);

Duration fiveHours = Duration.ofHours(5);

// adding five hours to the current
// time and storing it in time2
LocalTime time2 = time1.plus(fiveHours);

System.out.println("after adding five hours of duration " + time2);

Duration gap = Duration.between(time2, time1);
System.out.println("duraion gap between time1 & time2 is " + gap);
}

// Driver code
public static void main(String[] args) {
checkingPeriod();
checkingDuraion();
}
}

输出:

1
2
3
4
gap between dates is a period of P3Y3M28D
the current time is 06:21:18.248
after adding five hours of duration 11:21:18.248
duraion gap between time1 & time2 is PT-5H
  1. ChronoUnits枚举: Java 8中添加了java.time.temporal.ChronoUnit枚举,以替换旧API中用于表示日、月等等的整数值。
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
// Java code for ChronoUnits Enum 
import java.time.LocalDate;
import java.time.temporal.ChronoUnit;

public class Geeksforgeeks {

// Function to check ChronoUnit
public static void checkingChronoEnum()
{
LocalDate date = LocalDate.now();
System.out.println("current date is :" + date);

// adding 2 years to the current date
LocalDate year = date.plus(2, ChronoUnit.YEARS);

System.out.println("next to next year is " + year);

// adding 1 month to the current data
LocalDate nextMonth = date.plus(1, ChronoUnit.MONTHS);

System.out.println("the next month is " + nextMonth);

// adding 1 week to the current date
LocalDate nextWeek = date.plus(1, ChronoUnit.WEEKS);

System.out.println("next week is " + nextWeek);

// adding 2 decades to the current date
LocalDate Decade = date.plus(2, ChronoUnit.DECADES);

System.out.println("20 years after today " + Decade);
}

// Driver code
public static void main(String[] args) {

checkingChronoEnum();

}
}

输出:

1
2
3
4
5
current date is :2020-04-09
next to next year is 2020-04-09
the next month is 2020-05-09
next week is 2020-04-16
20 years after today 2020-04-09
  1. TemporalAdjuster:用于执行各种与日期相关的操作。
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
// Java code Temporal Adjuster 
import java.time.LocalDate;
import java.time.temporal.TemporalAdjusters;
import java.time.DayOfWeek;

public class Geek {

// Function to check date and time
// according to our requirement
public static void checkingAdjusters() {

LocalDate date = LocalDate.now();
System.out.println("the current date is "+ date);

// to get the first day of next month
LocalDate dayOfNextMonth = date.with(TemporalAdjusters.firstDayOfNextMonth());

System.out.println("firstDayOfNextMonth : " + dayOfNextMonth );

// get the next saturday
LocalDate nextSaturday = date.with(TemporalAdjusters.next(DayOfWeek.SATURDAY));

System.out.println("next satuday from now is "+ nextSaturday);

// first day of current month
LocalDate firstDay = date.with(TemporalAdjusters.firstDayOfMonth());

System.out.println("firstDayOfMonth : " + firstDay);

// last day of current month
LocalDate lastDay = date.with(TemporalAdjusters.lastDayOfMonth());

System.out.println("lastDayOfMonth : " + lastDay);
}

// Driver code
public static void main(String[] args)
{
checkingAdjusters();
}
}

输出

1
2
3
4
5
the current date is 2020-04-09
firstDayOfNextMonth : 2020-05-01
next satuday from now is 2020-04-14
firstDayOfMonth : 2020-04-01
lastDayOfMonth : 2020-04-30
给老奴加个鸡腿吧 🍨.