目录
什么是时区
由于世界各个国家与地区的经度不同,各地区的时间也有所不同,因此会划分为不同的时区。
// 目标:了解时区和带时区的时间。
// 1、ZoneId的常见方法:
// public static ZoneId systemDefault(): 获取系统默认的时区
ZoneId zoneId = ZoneId.systemDefault();
System.out.println("zoneId = " + zoneId);//zoneId = Asia/Shanghai
//
// // public static Set<String> getAvailableZoneIds(): 获取Java支持的全部时区Id
Set<String> availableZoneIds = ZoneId.getAvailableZoneIds();
// System.out.println("availableZoneIds = " + availableZoneIds);
// public static ZoneId of(String zoneId) : 把某个时区id封装成ZoneId对象。
ZoneId shanghai = ZoneId.of("Asia/Shanghai");
System.out.println("shanghai = " + shanghai);
// 2、ZonedDateTime:带时区的时间。
// public static ZonedDateTime now(ZoneId zone): 获取某个时区的ZonedDateTime对象。
ZonedDateTime now = ZonedDateTime.now();
System.out.println("now = " + now);
// public static ZonedDateTime now():获取系统默认时区的ZonedDateTime对象
ZoneId newYork = ZoneId.of("America/New_York");
//获取纽约时间
ZonedDateTime now1 = ZonedDateTime.now(newYork);
System.out.println("now1 = " + now1);
instant时间线上的某个时刻/时间戳
通过获取Instant的对象可以拿到此刻的时间,该时间由两部分组成∶从1970-01-01 00:00:00开始走到此刻的总秒数+不够1秒的纳秒数。
public static void main(String[] args) {
// 1、创建Instant的对象,获取此刻时间信息
Instant now = Instant.now();
System.out.println("获取此刻时间信息 = " + now);
// 2、获取总秒数
long epochSecond = now.getEpochSecond();
System.out.println("获取总秒数 = " + epochSecond);
// 3、某一秒开始计算的纳秒数
int nano = now.getNano();
System.out.println("纳秒 = " + nano);
// Instant对象的作用:做代码的性能分析,或者记录用户的操作时间点
Instant now1 = Instant.now();
// 代码执行。。。。
System.out.println("HelloWorld!");//计算执行输出HelloWorld需要多少时间
Instant now2 = Instant.now();
long second = now2.getEpochSecond() - now1.getEpochSecond();//秒差
int nano2 = now2.getNano() - now1.getNano();//纳秒差
System.out.println(second +":"+ nano2);//0:83000
}
作用:
可以用来记录代码的执行时间,或用于记录用户操作某个事件的时间点。
传统的Date类,只能精确到毫秒,并且是可变对象;
新增的Instant类,可以精确到纳秒,并且是不可变对象,推荐用Instant代替Date.