java根據時間date獲取該時間距離現在的時間間隔

最近的項目中有這樣一個需求,根據用戶上次的登錄時間判斷上次登錄距今有多久。

package com.pf.bindDate.utils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
 
public class TimeUtils {
 
    private final static long YEAR = 1000 * 60 * 60 * 24 * 365L;
    private final static long MONTH = 1000 * 60 * 60 * 24 * 30L;
    private final static long DAY = 1000 * 60 * 60 * 24L;
    private final static long HOUR = 1000 * 60 * 60L;
    private final static long MINUTE = 1000 * 60L;
 
    /**
     * 日期轉換成字符串
     * @param date
     * @return str
     */
    public static String dateToStr(Date date) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String str = format.format(date);
        return str;
    }
 
    /**
     * 字符串轉換成日期
     * @param str
     * @return date
     */
    public static Date strToDate(String str) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = null;
        try {
            date = format.parse(str);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return date;
    }
 
    /**
     * 根據時間查詢時間屬於哪個時刻
     * @param date
     * @return
     */
    public static String natureTime(Date date){
        Date now = new Date();
        long between = now.getTime() - date.getTime();
        if (between > YEAR){
            return ((between - YEAR) / YEAR + 1) + "年前 ";
        }
        if (between > MONTH){
            return ((between - MONTH) / MONTH + 1) + "月前 ";
        }
        if (between > DAY){
            return ((between - DAY) / DAY + 1) + "天前 ";
        }
        if (between > HOUR){
            return ((between - HOUR) / HOUR + 1) + "小時前 ";
        }
        if (between > MINUTE){
            return ((between - MINUTE) / MINUTE + 1) + "分鐘前 ";
        }
        return "剛剛,";
    }
 
	
	  public static void main(String [] args){ String str = "2020-03-05 17:25:07";
	  Date date = TimeUtils.strToDate(str);
	  System.out.println(TimeUtils.natureTime(date)); }
	 
 
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章