当前位置:网站首页>日期工具类

日期工具类

2022-08-09 10:46:00 'LYong

package com.unionx.core.util;


import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;

import net.sf.json.JSONArray;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;

/**
 * 日期工具类
 *
 * @author 宋俊杰
 * @version 1.0
 */
public class DateUtils extends org.apache.commons.lang3.time.DateUtils{
    private static Logger log = Logger.getLogger(DateUtils.class);

    /**
     * 根据一个给定的日期格式返回当前时间
     *
     * @param pattern 给定的日期时间格式
     * @return
     */
    public static String getCurrentDate(String pattern) {
        DateFormat dateFormat = new SimpleDateFormat(pattern);
        return dateFormat.format(new Date());
    }

    /**
     * 将日期字符串转换成日期类型
     *
     * @param dateStr 日期字符串
     * @param pattern 日期字符串的格式。如果没有指定(null或者"")默认为yyyy-MM-dd HH:mm:ss
     * @return
     */
    public static Date stringToDate(String dateStr, String pattern) {
        if (StringUtils.isBlank(pattern)) {
            pattern = "yyyy-MM-dd HH:mm:ss";
        }
        if (StringUtils.isNotEmpty(dateStr)) {
            try {
                return new SimpleDateFormat(pattern).parse(dateStr);
            } catch (ParseException e) {
                throw new RuntimeException(e);
            }
        }
        return null;
    }

    /**
     * 将一个字符串类型的时间转换为另一种格式的字符串类型时间
     * Example : String formattedDate = DateUtils.format("20070906112351", "yyyyMMddHHmmss", "yyyy年MM月dd日 HH时mm分ss秒")
     *
     * @param date          字符串类型时间.例如20070906112351
     * @param sourcePattern 源时间的格式
     * @param targetPattern 要转换的目标格式
     * @return
     */
    public static String convert(String date, String sourcePattern, String targetPattern) {
        if (StringUtils.isBlank(date)) {
            return "";
        }
        DateFormat _formater1 = new SimpleDateFormat(sourcePattern);
        DateFormat _formater2 = new SimpleDateFormat(targetPattern);
        try {
            return _formater2.format(_formater1.parse(date));
        } catch (ParseException pe) {
            return date;
        }
    }

    /**
     * 判断一个时间是否为上午
     *
     * @param date
     * @return boolean
     */
    public static boolean isAM(Date date) {
        boolean isTrue = true;
        DateFormat df = new SimpleDateFormat("HH");
        try {
            int integerHour = Integer.parseInt(df.format(date));
            if (integerHour >= 0 && integerHour <= 12) {
                isTrue = true;
            } else {
                isTrue = false;
            }
        } catch (NumberFormatException nfe) {
            throw new RuntimeException(nfe);
        }
        return isTrue;
    }

    /**
     * 增加指定天数。
     *
     * @param advanceDay 要增加的天数,可以为负数,如果为负数表示减少天数
     * @param pattren 返回的日期格式,如果没有指定默认是yyyyMMdd
     * @return 增加的后的时间
     */
    public static String addDay(int advanceDay, String pattren) {
        if (StringUtils.isBlank(pattren)) {
            pattren = "yyyyMMdd";
        }
        SimpleDateFormat format = new SimpleDateFormat(pattren);
        GregorianCalendar d = new GregorianCalendar();
        d.add(Calendar.DAY_OF_MONTH, advanceDay);
        return format.format(d.getTime());
    }
    
    /**
     * 
     * Description:
     * @param advanceDay
     * @param pattren
     * @return
     * @return String
     * @author name:
     *
     */
    public static String calculateDay(Date dateTime, int advanceDay, String pattren) {
        if (StringUtils.isBlank(pattren)) {
            pattren = "yyyyMMdd";
        }
        SimpleDateFormat format = new SimpleDateFormat(pattren);
        GregorianCalendar d = new GregorianCalendar();
        d.setTime(dateTime);
        d.add(Calendar.DAY_OF_MONTH, advanceDay);
        return format.format(d.getTime());
    }
    
    /**
     * 将日期转换成当天日期的最后时间(23时59分59秒999毫秒)。
     * @param date
     * @param pattern 可选参数,如果为null或者"",默认格式为yyyyMM
     * @return
     */
    public static Date getEndDatetime(String date,String pattern){
        if(StringUtils.isBlank(pattern)){
            pattern = "yyyyMMdd";
        }
        Date date1 = stringToDate(date, pattern);
        return getEndDatetime(date1);
    }

    /**
     * 返回给定日期的最后时间(23时59分59秒999毫秒)。
     * @param date
     * @return
     */
    public static Date getEndDatetime(Date date){
        if(date==null){
            return null;
        }
        date = DateUtils.setHours(date, 23);
        date = DateUtils.setMinutes(date, 59);
        date = DateUtils.setSeconds(date, 59);
        date = DateUtils.setMilliseconds(date, 999);
        return date;
    }

    /**
     * 经日期对象转换成字符串形式
     * @param date
     * @param pattern 指定要转成的日期格式
     * @return
     */
    public static String format(Date date , String pattern) {
        SimpleDateFormat sdf = new SimpleDateFormat(pattern);
        return sdf.format(date);
    }

    public static Date  GetDate(){
    	return new Date();
    }
    
    /**
     * 
     * 描述:获取下一个月的第一天.
     * 
     * @return
     */
    public static String getPerFirstDayOfMonth() {
        SimpleDateFormat dft = new SimpleDateFormat("yyyy-MM-dd");
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.MONTH, 1);
        calendar.set(Calendar.DAY_OF_MONTH, calendar.getActualMinimum(Calendar.DAY_OF_MONTH));
        return dft.format(calendar.getTime());
    }
    
    public static String getPerFirstDayOfMonth(Date date) {
        SimpleDateFormat dft = new SimpleDateFormat("yyyy-MM-dd");
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.add(Calendar.MONTH, 1);
        calendar.set(Calendar.DAY_OF_MONTH, calendar.getActualMinimum(Calendar.DAY_OF_MONTH));
        return dft.format(calendar.getTime());
    }
    
    /**
     * 
     * 描述:获取上个月的最后一天.
     * 
     * @return
     */
    public static String getLastMaxMonthDate() {
        SimpleDateFormat dft = new SimpleDateFormat("yyyy-MM-dd");
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());
        calendar.add(Calendar.MONTH, -1);
        calendar.set(Calendar.DAY_OF_MONTH, calendar.getActualMaximum(Calendar.DAY_OF_MONTH));
        return dft.format(calendar.getTime());
    }
    
    public static String getLastMaxMonthDate(Date date) {
        SimpleDateFormat dft = new SimpleDateFormat("yyyy-MM-dd");
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.add(Calendar.MONTH, -1);
        calendar.set(Calendar.DAY_OF_MONTH, calendar.getActualMaximum(Calendar.DAY_OF_MONTH));
        return dft.format(calendar.getTime());
    }
    
    /**
     * 获取当前月份最后一天
     * 
     * @param date
     * @return
     * @throws ParseException
     */
    public static String getMaxMonthDate() {
        SimpleDateFormat dft = new SimpleDateFormat("yyyy-MM-dd");
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());
        // calendar.add(Calendar.MONTH, -1);
        calendar.set(Calendar.DAY_OF_MONTH, calendar.getActualMaximum(Calendar.DAY_OF_MONTH));
        return dft.format(calendar.getTime());
    }
    
    public static String getMaxMonthDate(Date date) {
        SimpleDateFormat dft = new SimpleDateFormat("yyyy-MM-dd");
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        // calendar.add(Calendar.MONTH, -1);
        calendar.set(Calendar.DAY_OF_MONTH, calendar.getActualMaximum(Calendar.DAY_OF_MONTH));
        return dft.format(calendar.getTime());
    }
    
    /**
     * 获取当前月份第一天
     * @param date
     * @return
     * @throws ParseException
     */
    public static String getMinMonthDate(){
    	SimpleDateFormat dft = new SimpleDateFormat("yyyy-MM-dd");
    	//获取当前月第一天:
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());
        calendar.add(Calendar.MONTH, 0);
        calendar.set(Calendar.DAY_OF_MONTH,1);//设置为1号,当前日期既为本月第一天
        return dft.format(calendar.getTime());
    }
    
    /**
     * 
     * Description:获取月份的第五天
     * @return
     * @return String
     * @author name:
     *
     */
    public static String getFiveMonthDate(Date date){
    	SimpleDateFormat dft = new SimpleDateFormat("yyyy-MM-dd");
    	//获取当前月第一天:
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.add(Calendar.MONTH, 0);
        calendar.set(Calendar.DAY_OF_MONTH,5);//设置为5号,当前日期既为本月第一天
        return dft.format(calendar.getTime());
    }
    /**
     * 
     * Description:两段时间相差几个月
     * @param startDate
     * @param endDate
     * @return
     * @return int
     * @author name:
     *
     */
    public static int getMonths(Date startDate, Date endDate) {
        Calendar startCalendar = new GregorianCalendar();
        startCalendar.setTime(startDate);
        Calendar endCalendar = new GregorianCalendar();
        endCalendar.setTime(endDate);

        int diffYear = endCalendar.get(Calendar.YEAR) - startCalendar.get(Calendar.YEAR);
        int diffMonth = diffYear * 12 + endCalendar.get(Calendar.MONTH) - startCalendar.get(Calendar.MONTH);
        return diffMonth;
    }
    
    /**
     * 
     * Description:类型为0获取dd  类型为1获取yyyy-mm-dd
     * @param dateFirst
     * @param dateSecond
     * @return
     * @return JSONArray
     * @author name:
     * @param i 
     * @throws ParseException 
     *
     */
    public static JSONArray display(Date dateFirst, Date dateSecond, int i){
    	JSONArray arr = new JSONArray();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
            //Date dateOne = dateFormat.parse(dateFirst);
            //Date dateTwo = dateFormat.parse(dateSecond);
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(dateFirst);
            while(calendar.getTime().before(dateSecond)){              
                if(i == 0){
                	Calendar cal = Calendar.getInstance();
            		cal.setTime(calendar.getTime());//入职时间
            		int entryDay =cal.get(Calendar.DATE);//获取日
            		arr.add(entryDay);
                }else{
                	arr.add(dateFormat.format(calendar.getTime()));
                }
                calendar.add(Calendar.DAY_OF_MONTH, 1);  
            }
         return arr;
    }
    
    /** 
     * 时间加减月数
     * @param startDate 要处理的时间,Null则为当前时间 
     * @param months 加减的月数 
     * @return Date 
     */  
    public static Date dateAddMonths(Date startDate, int months) {  
        if (startDate == null) {  
            startDate = new Date();  
        }  
        Calendar c = Calendar.getInstance();  
        c.setTime(startDate);  
        c.set(Calendar.MONTH, c.get(Calendar.MONTH) + months);  
        return c.getTime();  
    }
    
    /** 
     * 时间加减年数
     * @param startDate 要处理的时间,Null则为当前时间 
     * @param years 加减的年数 
     * @return Date 
     */  
    public static Date dateAddYears(Date startDate, int years) {  
        if (startDate == null) {  
            startDate = new Date();  
        }  
        Calendar c = Calendar.getInstance();  
        c.setTime(startDate);  
        c.set(Calendar.YEAR, c.get(Calendar.YEAR) + years);  
        return c.getTime();  
    }
    
    /**
     * 
     * Description:获取近六个月的时间
     * @param sourceDate
     * @param month
     * @return
     * @throws ParseException
     * @return ArrayList<String>
     * @author name
     *
     */
    public static  ArrayList<String> stepMonth() throws ParseException {
    	Calendar c = Calendar.getInstance();
        c.add(Calendar.MONTH, -4);
        String before_six = c.get(Calendar.YEAR) + "-" + c.get(Calendar.MONTH);//六个月前
        ArrayList<String> result = new ArrayList<String>();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");// 格式化为年月
        Calendar min = Calendar.getInstance();
        Calendar max = Calendar.getInstance();
        min.setTime(sdf.parse(before_six));
        min.set(min.get(Calendar.YEAR), min.get(Calendar.MONTH), 1);
        max.setTime(sdf.parse(sdf.format(new Date())));
        max.set(max.get(Calendar.YEAR), max.get(Calendar.MONTH), 2);
        Calendar curr = min;
        while (curr.before(max)) {
            result.add(sdf.format(curr.getTime()));
            curr.add(Calendar.MONTH, 1);
        }
        //去除当前月
        //result.remove(result.size()-1);
		return result;
    }
    
    /**
     * 
     * Description:判断当前时间是否在[startTime, endTime]区间,注意时间格式要一致
     * @param nowTime
     * @param startTime
     * @param endTime
     * @return
     * @return boolean
     * @author name
     *
     */
    public static boolean isEffectiveDate(Date nowTime, Date startTime, Date endTime) {
        if (nowTime.getTime() == startTime.getTime()
                || nowTime.getTime() == endTime.getTime()) {
            return true;
        }

        Calendar date = Calendar.getInstance();
        date.setTime(nowTime);

        Calendar begin = Calendar.getInstance();
        begin.setTime(startTime);

        Calendar end = Calendar.getInstance();
        end.setTime(endTime);

        if (date.after(begin) && date.before(end)) {
            return true;
        } else {
            return false;
        }
    }
    

public static void main(String[] args) throws ParseException {
        /*Calendar c = Calendar.getInstance();
        c.add(Calendar.MONTH, -4);
        String before_six = c.get(Calendar.YEAR) + "-" + c.get(Calendar.MONTH);//六个月前
        ArrayList<String> result = new ArrayList<String>();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");// 格式化为年月
        Calendar min = Calendar.getInstance();
        Calendar max = Calendar.getInstance();
        min.setTime(sdf.parse(before_six));
        min.set(min.get(Calendar.YEAR), min.get(Calendar.MONTH), 1);
        max.setTime(sdf.parse(sdf.format(new Date())));
        max.set(max.get(Calendar.YEAR), max.get(Calendar.MONTH), 2);
        Calendar curr = min;
        while (curr.before(max)) {
            result.add(sdf.format(curr.getTime()));
            curr.add(Calendar.MONTH, 1);
        }*/
        //result.remove(result.size()-1);
        System.out.println();
    }

}
原网站

版权声明
本文为['LYong]所创,转载请带上原文链接,感谢
https://blog.csdn.net/weixin_39093006/article/details/112478329