java8 Instant.now()遇到的问题

在java.util.Date类与LocalDate、LocalDateTime类之间转换中
均可以通过Instant作为中间类完成转换,Instant的使用还是比较方便的,下面介绍Instant的使用。

一、创建Instant实例

Instant now = Instant.now();
System.out.println("now:"+now);

控制台输出:

2020-09-08T07:40:40.984Z

注意:通过这种方式获取的时间戳与北京时间相差8个时区,需要修正为北京时间,通过查看源代码发现Instant.now()使用等是UTC时间Clock.systemUTC().instant()。LocalDate、LocalDateTime 的now()方法使用的是系统默认时区 不存在Instant.now()的时间问题。
###解决方法
增加8个小时

Instant now = Instant.now().plusMillis(TimeUnit.HOURS.toMillis(8));
System.out.println("now:"+now);

控制台输出:

2020-09-08T15:40:40.984Z

二、Instant获取long类型的10位秒数、13位毫秒数

Instant now = Instant.now().plusMillis(TimeUnit.HOURS.toMillis(8));
System.out.println("秒数:"+now.getEpochSecond());
System.out.println("毫秒数:"+now.toEpochMilli());

控制台输出:

秒数:1539170157
毫秒数:1539170157886

LocalDateTime输出毫秒数的方式,比Instant多一步转换

LocalDateTime localDateTime = LocalDateTime.now();
//LocalDateTime转Instant
Instant localDateTime2Instant = localDateTime.atZone(ZoneId.systemDefault()).toInstant();
System.out.println("LocalDateTime 毫秒数:"+localDateTime2Instant.toEpochMilli());

控制台输出:

LocalDateTime 毫秒数:1539141733010

import java.time.*;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.Date;

/**
 * @author : yewang
 * create at:  2020/9/8  2:33 下午
 */
public class Main {


    //获取当前日期
    public static void getCurrentDate(){
        LocalDate today = LocalDate.now();
        System.out.println("Todays Local date:" + today);
        Date date = new Date();
        System.out.println(date);
    }
    //获取年月日信息
    public static void getDetailDate(){
        LocalDate today = LocalDate.now();
        int year = today.getYear();
        int month = today.getMonthValue();
        int day = today.getDayOfMonth();
        System.out.println(year);
        System.out.println(month);
        System.out.println(day);
    }

    //处理特定日期
    public static void handleSpecialDate(){
        LocalDate dateOfToday = LocalDate.of(2020, 9, 3);
        System.out.println(dateOfToday);
    }

    //判断两个日期是否相等
    public static void compareDate(){
        LocalDate today = LocalDate.now();
        LocalDate date1 = LocalDate.of(2020 , 9, 8);
        if(date1.equals(today)){
            System.out.printf("today %s and date1 %s is sameday",today,date1);
            System.out.println();
        }
    }

    //检查像生日这种周期性事件
    public static void cycleDate(){
        LocalDate today = LocalDate.now();
        LocalDate dateOfBitrh = LocalDate.of(2018, 9, 8);
        MonthDay birthday = MonthDay.of(dateOfBitrh.getMonth(), dateOfBitrh.getDayOfMonth());
        MonthDay currentMonthDay = MonthDay.from(today);
        if (birthday.equals(currentMonthDay)) {
            System.out.println("Happy Birthday!");
        }else{
            System.out.println("Sorry ,today is not your birthday!");
        }
    }
    //获取当前时间
    public static void getCurrentTime(){
        LocalTime now = LocalTime.now();
        System.out.println("local time :" + now);
    }

    //增加小时
    public static void plusHours(){
        LocalTime now = LocalTime.now();
        LocalTime newTime = now.plusHours(4);
        System.out.println(newTime);
    }
    //计算一星期后的日期
    public static void nextWeek(){
        LocalDate today = LocalDate.now();
        LocalDate nextWeek = today.plusDays(7);
        System.out.println("nextWeek is:" + nextWeek);
    }
    //计算一年前或者一年后的日期
    public static void minusDate(){
        LocalDate today = LocalDate.now();
        LocalDate previousYear = today.minus(1, ChronoUnit.YEARS);
        System.out.println("Date before 1 year:" + previousYear);
        LocalDate nextYear = today.plus(1, ChronoUnit.YEARS);
        System.out.println("Date next 1year:" + nextYear);
    }
    //获取时钟类
    public static void clock(){
        // 根据系统时间返回当前时间并设置为UTC。
        Clock clock = Clock.systemUTC();
        System.out.println("Clock : " + clock);

        // 根据系统时钟区域返回时间
        Clock defaultClock = Clock.systemDefaultZone();
        System.out.println("Clock : " + clock);
    }
    //如何用Java判断日期是早于还是晚于另一个日期
    public static void isBeforeOrIsAfter(){
        LocalDate today = LocalDate.now();

        LocalDate tomorrow = LocalDate.of(2018, 1, 29);
        if(tomorrow.isAfter(today)){
            System.out.println("Tomorrow comes after today");
        }

        //减去一天
        LocalDate yesterday = today.minus(1, ChronoUnit.DAYS);

        if(yesterday.isBefore(today)){
            System.out.println("Yesterday is day before today");
        }
    }

    //获取特定时区下面的时间
    public static void getZoneTime(){
        //设置时区
        ZoneId america = ZoneId.of("America/New_York");

        LocalDateTime localtDateAndTime = LocalDateTime.now();

        ZonedDateTime dateAndTimeInNewYork  = ZonedDateTime.of(localtDateAndTime, america );
        System.out.println("现在的日期和时间在特定的时区 : " + dateAndTimeInNewYork);
    }
    //使用 YearMonth类处理特定的日期
    public static void checkCardExpiry(){
        YearMonth currentYearMonth = YearMonth.now();
        System.out.printf("Days in month year %s: %d%n", currentYearMonth, currentYearMonth.lengthOfMonth());

        YearMonth creditCardExpiry = YearMonth.of(2028, Month.FEBRUARY);
        System.out.printf("Your credit card expires on %s %n", creditCardExpiry);
    }
    //检查闰年
    public static void isLeapYear(){
        LocalDate today = LocalDate.now();
        if(today.isLeapYear()){
            System.out.println("This year is Leap year");
        }else {
            System.out.println("2020 is not a Leap year");
        }
    }
    //计算两个日期之间的天数和月数
    public static void calcDateDays(){
        LocalDate today = LocalDate.now();

        LocalDate java8Release = LocalDate.of(2018, Month.MAY, 14);

        Period periodToNextJavaRelease = Period.between(today, java8Release);

        System.out.println("Months left between today and Java 8 release : "
                + periodToNextJavaRelease.getMonths() );
    }
    public static void getTimestamp(){
        Instant timestamp = Instant.now();
        System.out.println("What is value of this instant " + timestamp);
    }
    // 使用预定义的格式化工具去解析或格式化日期
    public static void formateDate(){
        String dayAfterTommorrow = "20180210";
        LocalDate formatted = LocalDate.parse(dayAfterTommorrow, DateTimeFormatter.BASIC_ISO_DATE);
        System.out.printf("Date generated from String %s is %s %n", dayAfterTommorrow, formatted);
    }
    public static void main(String[] args) {
        getCurrentDate();
        getDetailDate();
        handleSpecialDate();
        compareDate();
        cycleDate();
        getCurrentTime();
        plusHours();
        nextWeek();
        minusDate();
        clock();
        isBeforeOrIsAfter();
        getZoneTime();
        checkCardExpiry();
        isLeapYear();
        calcDateDays();
        getTimestamp();
        formateDate();
    }

}

相关推荐
©️2020 CSDN 皮肤主题: 撸撸猫 设计师:马嘣嘣 返回首页