Java8Time
今天是:
我需要三件东西:爱情友谊和图书。然而这三者之间何其相通!炽热的爱情可以充实图书的内容,图书又是人们最忠实的朋友。
User Image Java8Time 05/May/2021
1.时间转换
@Test
//LocalDateTime转long
public  void java8TimeLocalTimeDateToLong(){
    LocalDateTime now = LocalDateTime.now();
    long  milliLongTime= now.toInstant(ZoneOffset.of("+8")).toEpochMilli();//毫秒级
    long  secondLongTime= now.toInstant(ZoneOffset.of("+8")).getEpochSecond();//秒级
    System.out.println(milliLongTime);
    System.out.println(secondLongTime);
}
@Test
//long转LocalDateTime
public  void Java8TimeLongToLocalTimeDate(){
    long currTime =LocalDateTime.now().toInstant(ZoneOffset.of("+8")).toEpochMilli();;
    LocalDateTime localDateTime=  LocalDateTime.ofInstant(Instant.ofEpochMilli(currTime), TimeZone.getDefault().toZoneId());
    System.out.println(localDateTime.toString());
}


@Test
//String转LocalDateTime
public  void Java8TimeStingToLocalTimeDate(){
    String timeStr="2021-05-04 21:12:10";
    LocalDateTime  stringTime= LocalDateTime.parse(timeStr, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss", Locale.getDefault()));
    System.out.println(Locale.getDefault());
    System.out.println(stringTime.toString());
}

@Test
//LocalDateTime转String
public  void Java8TimeLocalTimeDateToString(){
    LocalDateTime now = LocalDateTime.now();
    String timeStr= now.format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss"));
    System.out.println(timeStr);
}

 

@Test
//LocalDateTime转java.util.Date
public  void Java8TimeLocalTimeDateToDate(){
    LocalDateTime now = LocalDateTime.now();
    Date date = Date.from(now.atZone(ZoneId.systemDefault()).toInstant());
    System.out.println(date);
}


@Test
//java.util.Date转LocalDateTime
public  void DateToJava8TimeLocalTimeDate(){
    LocalDateTime ldt = new Date().toInstant()
            .atZone( ZoneId.systemDefault() )
            .toLocalDateTime();
    System.out.println(ldt);
}

 

java 8 时间API

分享到:

专栏

类型标签

外部链接

网站访问总量