java 8日期相关类
Instant:精确到纳秒的时间戳
Duration:处理有关基于时间的时间量
LocalDate:只包含日期,比如:2016-10-20
LocalTime:只包含时间,比如:23:12:10
LocalDateTime:包含日期和时间,比如:2016-10-20 23:14:21
Period:处理有关基于时间的日期数量
ZoneOffset:时区偏移量,比如:+8:00
ZonedDateTime:带时区的时间
Clock:时钟,比如获取目前美国纽约的时间
日期格式化类:DateTimeFormatter
示例:
DateTimeFormatter formatter1 = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
LocalDateTime localDateTime = LocalDateTime.now();
System.out.printf("localDateTime:" + localDateTime.format(formatter1) + "\n");
DateTimeFormatter formatter2 = DateTimeFormatter.ofPattern("yyyy-MM-dd");
LocalDate localDate = LocalDate.now();
System.out.printf("localDate:" + localDate.format(formatter2) + "\n");
System.out.printf("本月第一天:" + localDate.withDayOfMonth(1) + "\n");
System.out.printf("本月第一天:" + localDate.with(TemporalAdjusters.firstDayOfMonth()) + "\n");
Clock clock = Clock.systemDefaultZone();
Instant instant=clock.instant();
System.out.printf("Instant:" + instant);
java8 之前日期相关类
Calendar
Date
Timestamp
例:
Date date = new Date(); // 获取当前的系统时间
System.out.println("年份:"+ date.getYear());
Calendar calendar = Calendar.getInstance(); //获取当前的系统时间。
System.out.println("年:"+ calendar.get(Calendar.YEAR));
System.out.println("月:"+ (calendar.get(Calendar.MONTH)+1)); System.out.println("日:"+ calendar.get(Calendar.DATE));
System.out.println("时:"+ calendar.get(Calendar.HOUR_OF_DAY));
System.out.println("分:"+ calendar.get(Calendar.MINUTE));
System.out.println("秒:"+ calendar.get(Calendar.SECOND));
日期格式化类:SimpleDateFormat
例:
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
System.out.printf("date:" + format.format(new Date()) + "\n");
Calendar calendar = Calendar.getInstance();
System.out.printf("calendar:" + format.format(calendar.getTime()) + "\n");