JAVA8 常用的日期时间方法

JAVA8 更新了原本线程不安全的SimpleDateFormat, 新的DateTimeFormatter则是线程安全的。

下面列出JAVA8开发中常用的时间操作。

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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
import java.time.DayOfWeek;
import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.Month;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoField;

public class TimeTest {
public static void main(String[] args) {
// 获取当前年月日 - 2019-11-06
LocalDate nowDate = LocalDate.now();
// 2019
int nowYear = nowDate.getYear();
// 2019
int nowYear1 = nowDate.get(ChronoField.YEAR);
// NOVEMBER
Month nowMonth = nowDate.getMonth();
// 11
int nowMonth1 = nowDate.get(ChronoField.MONTH_OF_YEAR);
// 6
int nowDay = nowDate.getDayOfMonth();
// 6
int nowDay1 = nowDate.get(ChronoField.DAY_OF_MONTH);
// WEDNESDAY
DayOfWeek dayOfWeek = nowDate.getDayOfWeek();
// 3
int dayOfWeek1 = nowDate.get(ChronoField.DAY_OF_WEEK);
// 获取当前时分秒 - 15:16:24.401
LocalTime nowTime = LocalTime.now();
// 指定时分秒 - 12:51:10
LocalTime nowTime1 = LocalTime.of(12, 51, 10);
// 指定时间 - 2019-11-06
LocalDate specificTime = LocalDate.of(2019, 11, 6);

// LocalDateTime 获取年月日时分秒
LocalDateTime localDateTime = LocalDateTime.now();
// 指定时间 2019-11-11T16:14:20
LocalDateTime localDateTime1 = LocalDateTime.of(2019, Month.NOVEMBER, 11, 16, 14, 20);
// 2019-11-06T16:19:51.506
LocalDateTime localDateTime2 = LocalDateTime.of(nowDate, nowTime);
// LocalDateTime localDateTime3 = LocalDat

// 获取毫秒数
// 获取当前时间 2019-11-06T07:18:39.956Z
Instant instant = Instant.now();
// 1573028684 得到的是秒数
long currentSecond = instant.getEpochSecond();
// 1573028779924 得到毫秒数
long currentMilli = instant.toEpochMilli();
// 获取当前年月日 - 2019-11-06
LocalDate date = Instant.ofEpochMilli(instant.toEpochMilli()).atZone(ZoneId.systemDefault()).toLocalDate();

// 格式化时间
// 2019-11-06
LocalDate localDate = LocalDate.of(2019, 11, 6);
// 20191106
String str1 = localDate.format(DateTimeFormatter.BASIC_ISO_DATE);
// 2019-11-06
String str2 = localDate.format(DateTimeFormatter.ISO_LOCAL_DATE);
// 自定义格式化
DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
// 2019-11-06 16:41:10
String str3 = localDateTime.format(dateTimeFormatter);
System.out.println(str3);
}
}
0%