JAVA 常用日期處理工具方法

 本文介紹了獲取長日期,短日期,年,月,周等日期處理的基本方法。

import org.springframework.stereotype.Component;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

/**
 * date util
 */
@Component
public final class DateUtil {

    /**
     * 獲取長日期
     * return yyyy-MM-dd HH:mm:ss
     */
    public static String getLongDateString() {
        Date date = new Date();
        SimpleDateFormat dateformat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String dateStr = dateformat.format(date);
        return dateStr;
    }

    /**
     * 獲取短日期
     * return yyyy-MM-dd
     */
    public static String getShortDateString() {
        Date date = new Date();
        SimpleDateFormat dateformat = new SimpleDateFormat("yyyy-MM-dd");
        String dateStr = dateformat.format(date);
        return dateStr;
    }




    /**
     * 獲取本週自然周次
     * return yyyyww
     */
    public static Integer getNowWeek() {
        Calendar c = Calendar.getInstance();
        int week = c.get(Calendar.WEEK_OF_YEAR);//獲取是本年的第幾周
        int year = c.get(Calendar.YEAR);//獲取年份
        return year*100+week;
    }




    /**
     * 獲取當前月份字符串,帶年
     * @return 201607 string
     */
    public static String getCurrentMonth() {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMM"); 
        return dateFormat.format(new Date());
    }


    /**
     * 獲取當前年份
     *
     * @return 201607 string
     */
    public static String getCurrentYear() {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy"); 
        return dateFormat.format(new Date());
    }

    /**
     * 判斷當前日期是星期幾 
     * 1,2,3,4,5,6,7 週一到週日
     * @param pTime 要判斷的時間
     * @return dayForWeek 判斷結果
     * @Exception 發生異常
     */
    public static Integer dayForWeek(String pTime) throws ParseException {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        Calendar c = Calendar.getInstance();
        c.setTime(format.parse(pTime));
        int dayForWeek = 0;
        if(c.get(Calendar.DAY_OF_WEEK) == 1){
            dayForWeek = 7;
        }else{
            dayForWeek = c.get(Calendar.DAY_OF_WEEK) - 1;
        }
        return dayForWeek;
    }


    /**
     * 獲取當前日期上一天的字符串,具體到某月某日
     * @return 20160705 string
     */
    public static String getLastDate() {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd"); //yyyyMMdd
        long times = System.currentTimeMillis()-86400000;
        return dateFormat.format(new Date(times));
    }

   
    /**
     * 獲取當前日期前/後n天的日期的字符串,具體到某月某日
     * @param n n爲正表示今天之後的n天,n爲負數表示今天之前的n天,n爲0表示今天。
     * @return 20160705 string
     */
    public static String getSpecificDate(int n) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd"); //yyyyMMdd
        long times = System.currentTimeMillis()+86400000*n;
        return dateFormat.format(new Date(times));
    }

  

    /**獲取間隔天數*/
    public static String getIntervalDays(String endDate,String startDate){

        if(endDate==null||startDate==null){
            return null;
        }
        try
        {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

            Date firstDate = sdf.parse(endDate);
            Date secondDate = sdf.parse(startDate);

            //得到兩個日期對象的總毫秒數
            long firstDateMilliSeconds = firstDate.getTime();
            long secondDateMilliSeconds = secondDate.getTime();

            //得到兩者之差
            long MinusSecond = firstDateMilliSeconds - secondDateMilliSeconds;

            //得到總天數
            String days = String.valueOf( MinusSecond / (1000*3600*24));
            return  days;
        }
        catch (ParseException e)
        {
            System.out.println(e.getMessage());
        }
        return null;
    }

    /**
     * 獲取月份, 0:當月, -1:上月, -2:上上月, ...; 1:下月, 2:下下月, ...
     * @param num
     * @return eg. 201608
     */
    public static String getCurrentMonth(int num) {
        if(num == 0)
            return getCurrentMonth();
        else
            return addMonth(getCurrentMonth(), num);
    }

    /**
     * @param currentMonth 201607
     * @return 201608
     */
    public static String nextMonth(String currentMonth) {
        return addMonth(currentMonth, 1);
    }

    /**
     * @param currentMonth 201607
     * @return 201606
     */
    public static String lastMonth(String currentMonth) {
        return addMonth(currentMonth, -1);
    }

    /**
     * @param monthStr 201607
     * @param num 增加的月數, 負值就是減少, eg:1
     * @return 201608 string
     */
    public static String addMonth(String monthStr, int num) {
        Calendar cal = Calendar.getInstance();
        cal.set(Calendar.YEAR, Integer.parseInt(monthStr.substring(0, 4)));
        cal.set(Calendar.MONTH, Integer.parseInt(monthStr.substring(4)) - 1);
        cal.add(Calendar.MONTH, num);
        return cal.get(Calendar.YEAR) + String.format("%02d", cal.get(Calendar.MONTH) + 1);
    }

   
    /**
     * 時間比較, 返回 1:timeStr1在timeStr2之前, 0:時間相等, -1:timeStr1在timeStr2之後
     * @param timeStr1
     * @param timeStr2
     * @return int
     */
    public static int timeBefore(String timeStr1, String timeStr2) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try{
            long time1 = format.parse(timeStr1).getTime();
            long time2 = format.parse(timeStr2).getTime();
            if (time1 < time2){
                return 1;
            } else if (time1 == time2) {
                return 0;
            } else {
                return -1;
            }
        }catch(Exception e){
            log.error("exception:",e);
        }
        return -1;
    }


    /**
     *  根據日期獲取自然周次:  注意:本方法以周天開頭
     * @param nowTime
     * @return 201951 (2019年51周)
     */
    public static String getNatureWeek(String nowTime) {
        SimpleDateFormat dateFormatter = new SimpleDateFormat("yyyy-MM-dd");
        Date date=null;
        try {
            date = dateFormatter.parse(nowTime);
        } catch (java.text.ParseException e) {
            log.error("error{}",e);
        }
        dateFormatter.applyPattern("yw");
        return dateFormatter.format(date);
    }

}

 

發佈了14 篇原創文章 · 獲贊 2 · 訪問量 1萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章