Java8中的LocalDateTime和Date一些时间操作

先记录下jdk8之前的一些帮助方法

判断time是否在now的n天之内

/**
     * 判断time是否在now的n天之内
     * @param time
     * @param now
     * @param n    正数表示在条件时间n天之后,负数表示在条件时间n天之前
     * @return
     */
    public static boolean belongDate(Date time, Date now, int n) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Calendar calendar = Calendar.getInstance();  //得到日历
        calendar.setTime(now);//把当前时间赋给日历
        calendar.add(Calendar.DAY_OF_MONTH, n);
        Date before7days = calendar.getTime();   //得到n前的时间
        if (before7days.getTime() < time.getTime()) {
            return true;
        } else {
            return false;
        }
    }

判断某个时间是否是在条件的起始时间与结束时间之内

/**
     * 判断time是否在from,to之内
     *
     * @param time 指定日期
     * @param from 开始日期
     * @param to   结束日期
     * @return
     */
    public static boolean belongCalendar(Date time, Date from, Date to) {
        Calendar date = Calendar.getInstance();
        date.setTime(time);
 
        Calendar after = Calendar.getInstance();
        after.setTime(from);
 
        Calendar before = Calendar.getInstance();
        before.setTime(to);
 
        if (date.after(after) && date.before(before)) {
            return true;
        } else {
            return false;
        }
    }

判断给定时间与当前时间相差多少天

public static long getDistanceDays(String date) {
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        long days = 0;
        try {
            Date time = df.parse(date);//String转Date
            Date now = new Date();//获取当前时间
            long time1 = time.getTime();
            long time2 = now.getTime();
            long diff = time1 - time2;
            days = diff / (1000 * 60 * 60 * 24);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return days;//正数表示在当前时间之后,负数表示在当前时间之前
    }

将Date转换成String

private static final String LONG_PATTERN="yyyy-MM-dd HH:mm:ss";
    private static final String SHORT_PATTERN="yyyy-MM-dd";

    /**
     * 将日期转换为字符串
     */
    public static String parse( Date d, String pattern){
        DateFormat df=null;
        if( pattern!=null && !"".equals(pattern) ){
            df=new SimpleDateFormat(pattern);
        }else{
            df=new SimpleDateFormat(LONG_PATTERN);
        }
        return df.format( d );
    }

将String转换成Date

 private static final String LONG_PATTERN="yyyy-MM-dd HH:mm:ss";
 private static final String SHORT_PATTERN="yyyy-MM-dd";

/**
     * 将字符串转为日期
     */
    public static Date parseStringToDate(String str, String pattern){
        DateFormat df = null;
        if( pattern!=null && !"".equals(pattern) ){
            df=new SimpleDateFormat( pattern );
        }else{
            df=new SimpleDateFormat( LONG_PATTERN );
        }
        Date d=null;
        try {
            d=df.parse(str);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return d;

    }

获取指定年后的日期(例如三年后的日期)

       Calendar date = Calendar.getInstance();
        date.setTime(new Date());
        date.add(Calendar.YEAR, +3);
        //倒计时结束后的时间
        Date scrap_year = date.getTime();
        System.out.println("三年后时间" + scrap_year);

Jdk8改革

LocalDateTime获取毫秒数

//获取秒数
Long second = LocalDateTime.now().toEpochSecond(ZoneOffset.of("+8"));
//获取毫秒数
Long milliSecond = LocalDateTime.now().toInstant(ZoneOffset.of("+8")).toEpochMilli();
 

LocalDateTime与String互转

//时间转字符串格式化
 DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMddHHmmssSSS");
 String dateTime = LocalDateTime.now(ZoneOffset.of("+8")).format(formatter);
 
//字符串转时间
String dateTimeStr = "2018-07-28 14:11:15";
DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
LocalDateTime dateTime = LocalDateTime.parse(dateTimeStr, df);

Date与LocalDateTime互转

//将java.util.Date 转换为java8 的java.time.LocalDateTime,默认时区为东8区
    public static LocalDateTime dateConvertToLocalDateTime(Date date) {
        return date.toInstant().atOffset(ZoneOffset.of("+8")).toLocalDateTime();
    }
 
   
    //将java8 的 java.time.LocalDateTime 转换为 java.util.Date,默认时区为东8区
    public static Date localDateTimeConvertToDate(LocalDateTime localDateTime) {
        return Date.from(localDateTime.toInstant(ZoneOffset.of("+8")));
    }

将LocalDateTime转为自定义的时间格式的字符串

public static String getDateTimeAsString(LocalDateTime localDateTime, String format) {
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern(format);
    return localDateTime.format(formatter);
}

将某时间字符串转为自定义时间格式的LocalDateTime

public static LocalDateTime parseStringToDateTime(String time, String format) {
    DateTimeFormatter df = DateTimeFormatter.ofPattern(format);
    return LocalDateTime.parse(time, df);
}

将long类型的timestamp转为LocalDateTime

public static LocalDateTime getDateTimeOfTimestamp(long timestamp) {
    Instant instant = Instant.ofEpochMilli(timestamp);
    ZoneId zone = ZoneId.systemDefault();
    return LocalDateTime.ofInstant(instant, zone);
}

将LocalDateTime转为long类型的timestamp

public static long getTimestampOfDateTime(LocalDateTime localDateTime) {
    ZoneId zone = ZoneId.systemDefault();
    Instant instant = localDateTime.atZone(zone).toInstant();
    return instant.toEpochMilli();
}

 

你可能感兴趣的:(JAVA基础知识点)