Java API的使用

Java8 新特性学习

      • LocalDateTime 计算天数差、时间差
      • Date 转 LocalDateTime

LocalDateTime 计算天数差、时间差

public class Test {

    public static void main(String[] args) {
        LocalDateTime now = LocalDateTime.now();
        LocalDateTime localDateTime = LocalDateTime.now().plusHours(2);
        Duration between = Duration.between(now, localDateTime);
        System.out.println("相差的天数: " + between.toDays());
        System.out.println("相差的小时数: " + between.toHours());
        System.out.println("相差的分钟数: " + between.toMinutes());
        System.out.println("相差毫秒数: " + between.toMillis());
        System.out.println("相差的纳秒数: " + between.toNanos());
		
		// LocalDate 时间差
		LocalDate of = LocalDate.of(2020, 6, 5);
        LocalDate localDate = Instant.ofEpochMilli(1590724649484L).atZone(ZoneOffset.ofHours(8)).toLocalDate();
		int days = Period.between(localDate, of).getDays();
    }
}
  • 控制台打印
相差的天数: 0
相差的小时数: 2
相差的分钟数: 120
相差毫秒数: 7200000
相差的纳秒数: 7200000000000

Date 转 LocalDateTime

public class Test {

    public static void main(String[] args) {
        Date date = new Date();
        Instant instant = date.toInstant();
        ZoneId zoneId = ZoneId.systemDefault();

        LocalDateTime localDateTime = instant.atZone(zoneId).toLocalDateTime();
        System.out.println("Date : " + date);
        System.out.println("LocalDateTime : " + localDateTime);

    }
}
  • 打印
Date:Mon May 18 11:36:05 CST 2020
LocalDateTime:2020-05-18T11:36:05.673
/**
 * 时间戳转换日期对象
 *
 * @param stamp 时间戳
 * @return Date对象
 */
public static Date stampToDate(String stamp) {
    long t = Long.parseLong(stamp);
    return new Date(t);
}

/**
 * 时间戳转LocalDateTime
 * @param stamp
 * @return
 */
public static LocalDateTime stampToLocalDateTime(String stamp){
    long t = Long.parseLong(stamp);
    Instant timestamp = Instant.ofEpochMilli(t);
    return LocalDateTime.ofInstant(timestamp, ZoneId.of(zone));
}
String nowTime = "2020-08-18 06:12:05 America/Los_Angeles";
String format = "yyyy-MM-dd HH:mm:ss 'America/Los_Angeles'";
LocalDateTime parse = LocalDateTime.parse(nowTime, DateTimeFormatter.ofPattern(format));

你可能感兴趣的:(经验总结)