-
新日期类简介
Java 8在java.time包下提供了很多的新API,以下两个比较重要- Local(本地) - 简化了日期时间的处理,没有时区的问题。
- Zoned(时区) - 通过制定的时区处理日期时间。
-
为什么还需要新的时期类
Java 8通过发布新的Date-time API来进一步加强对日期和时间的处理。- 非线程安全java.util.Date是非线程安全的,所有的日期都是可变的
- 设计很差,
- 时区处理麻烦。
-
如何使用
public class LocalTestDemo {
public static void main(String[] args) {
LocalDateTime now = LocalDateTime.now();
System.out.println(now);
//只要日期
//LocalDate dnow = LocalDate.now()
LocalDate dnow = now.toLocalDate();
System.out.println("现在日期"+dnow);
//只要时间
LocalTime tnow = now.toLocalTime();
System.out.println("现在时间"+tnow);
Month mouth = now.getMonth();
int day = now.getDayOfMonth();
int second = now.getSecond();
System.out.println("月"+mouth.getValue()+",日"+day+",秒"+second);
//返回值是localdatetime,now的返回值就是localdatetime,返回值是自己,所以可以继续调用
LocalDateTime date = now.withYear(2012).withDayOfMonth(10).withHour(20);
System.out.println("指定时间"+date);
//只修改年月日
LocalDate ddate = now.withYear(2008).withMonth(8).toLocalDate();
System.out.println("制定日期"+ddate);
//字符串转换
String time = "20:20:15";
LocalTime tt = LocalTime.parse(time).withHour(21);
System.out.println(tt);
//date转字符串直接调用tt.toString就可以
}
}
- date转字符串直接调用tt.toString就可以
- 定义时区
public class ZonedTestDemo {
public static void main(String[] args) {
ZonedDateTime now = ZonedDateTime.now();
System.out.println(now);
ZoneId id = now.getZone();
System.out.println(id);
ZoneId zid = ZoneId.of("Europe/Paris");
System.out.println(zid);
ZonedDateTime znow = now.withZoneSameInstant(zid);
System.out.println(znow);
}
}



