一、java8之前的时间
二、java8新添加的时间
LocalDate
LocalTime
LocalDateTime
Instant
ZoneId
ZoneOffset
OffsetDateTime
ZonedDateTime

@Test
public void localDateTime(){
    LocalDateTime  dateTime = LocalDateTime.now(ZoneId.systemDefault());
    //2022-04-24T17:30:58.264
    System.out.println(dateTime);
}

@Test
public void zonedDateTime(){
    ZonedDateTime now = ZonedDateTime.now();
    //2022-04-24T17:38:05.055+08:00[Asia/Shanghai]
    System.out.println(now);

    String newYork = "America/New_York";
    ZonedDateTime newYorkTime = ZonedDateTime.of(now.toLocalDateTime(), ZoneId.of(newYork));
    //2022-04-24T17:38:05.055-04:00[America/New_York]
    System.out.println(newYorkTime);
}
@Test
public void instanceToZonedDateTime(){
    Instant now = Instant.now();
    ZonedDateTime zonedDateTime = ZonedDateTime.ofInstant(now,ZoneId.systemDefault());
    //2022-04-24T17:34:02.632+08:00[Asia/Shanghai]
    System.out.println(zonedDateTime);

    String newYork = "America/New_York";
    ZonedDateTime newYorkTime = ZonedDateTime.ofInstant(now, ZoneId.of(newYork));
    //2022-04-24T05:34:02.632-04:00[America/New_York]
    System.out.println(newYorkTime);
}

@Test
public void format(){
    ZonedDateTime now = ZonedDateTime.now();
    //2022-04-24T17:49:18.911
    //2022-04-24T17:49:18.911+08:00[Asia/Shanghai]
    //2022-04-24T17:49:18.911+08:00
    System.out.println(now.format(DateTimeFormatter.ISO_LOCAL_DATE_TIME));
    System.out.println(now.format(DateTimeFormatter.ISO_ZONED_DATE_TIME));
    System.out.println(now.format(DateTimeFormatter.ISO_OFFSET_DATE_TIME));

    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss");
    LocalDateTime time = LocalDateTime.of(2022, 04, 24, 17, 50, 50);

    //2022/04/24 17:50:50
    System.out.println(time.format(formatter));
}

@Test
public void parse(){
        //2022-04-24T17:49:18.911
        //2022-04-24T17:49:18.911
        //2022-04-24T17:49:18.911
    System.out.println(LocalDateTime.parse("2022-04-24T17:49:18.911",DateTimeFormatter.ISO_LOCAL_DATE_TIME));
    System.out.println(LocalDateTime.parse("2022-04-24T17:49:18.911+08:00[Asia/Shanghai]",DateTimeFormatter.ISO_ZONED_DATE_TIME));
    System.out.println(LocalDateTime.parse("2022-04-24T17:49:18.911+08:00",DateTimeFormatter.ISO_OFFSET_DATE_TIME));

    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss");
    String string = "2022/04/24 17:55:52";
    //2022-04-24T17:55:52
    System.out.println(LocalDateTime.parse(string,formatter));
}

yinpursue
1 声望0 粉丝