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) { LocalDate nowDate = LocalDate.now(); int nowYear = nowDate.getYear(); int nowYear1 = nowDate.get(ChronoField.YEAR); Month nowMonth = nowDate.getMonth(); int nowMonth1 = nowDate.get(ChronoField.MONTH_OF_YEAR); int nowDay = nowDate.getDayOfMonth(); int nowDay1 = nowDate.get(ChronoField.DAY_OF_MONTH); DayOfWeek dayOfWeek = nowDate.getDayOfWeek(); int dayOfWeek1 = nowDate.get(ChronoField.DAY_OF_WEEK); LocalTime nowTime = LocalTime.now(); LocalTime nowTime1 = LocalTime.of(12, 51, 10); LocalDate specificTime = LocalDate.of(2019, 11, 6); LocalDateTime localDateTime = LocalDateTime.now(); LocalDateTime localDateTime1 = LocalDateTime.of(2019, Month.NOVEMBER, 11, 16, 14, 20); LocalDateTime localDateTime2 = LocalDateTime.of(nowDate, nowTime);
Instant instant = Instant.now(); long currentSecond = instant.getEpochSecond(); long currentMilli = instant.toEpochMilli(); LocalDate date = Instant.ofEpochMilli(instant.toEpochMilli()).atZone(ZoneId.systemDefault()).toLocalDate();
LocalDate localDate = LocalDate.of(2019, 11, 6); String str1 = localDate.format(DateTimeFormatter.BASIC_ISO_DATE); String str2 = localDate.format(DateTimeFormatter.ISO_LOCAL_DATE); DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); String str3 = localDateTime.format(dateTimeFormatter); System.out.println(str3); } }
|