Java日期处理相关工具类

package com.utils;

import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;

import org.apache.log4j.Logger;


/**
 * DateUtils.java 日期处理相关工具类
 */
public class DateUtil
{
    /**
     * 日志
     */
    private static final Logger LOGGER = Logger.getLogger(DateUtil.class);
    
    /** 定义常量 **/
    public static final String DATE_JFP_STR = "yyyyMM";
    
    /**
     * 时间格式 yyyy-MM-dd HH:mm:ss
     */
    public static final String DATE_FULL_STR = "yyyy-MM-dd HH:mm:ss";
    
    /**
     * 时间格式 yyyy-MM-dd
     */
    public static final String DATE_SMALL_STR = "yyyy-MM-dd";
    
    /**
     * 月初
     */
    public static final String BEGIN_MONTH = "yyyy-MM-01 00:00:00";
    
    /**
     * 时间格式 yyMMddHHmmss
     */
    public static final String DATE_KEY_STR = "yyMMddHHmmss";
    
    /**
     * 白天开始时间
     */
    private static final String DAYTIME_FROM = "06:30";
    /**
     * 晚上开始时间
     */
    private static final String DAYTIME_TO = "18:00";
    
    /**
     * 使用预设格式提取字符串日期
     * 
     * @param strDate 日期字符串
     * @return Date Date
     */
    public static Date parse(String strDate)
    {
        return parse(strDate, DATE_FULL_STR);
    }
    
    /**
     * 使用用户格式提取字符串日期
     * 
     * @param strDate 日期字符串
     * @param pattern 日期格式
     * @return Date Date
     */
    public static Date parse(String strDate, String pattern)
    {
        SimpleDateFormat df = new SimpleDateFormat(pattern);
        try
        {
            return df.parse(strDate);
        }
        catch (ParseException e)
        {
            LOGGER.error("日期:" + strDate + ",转化格式为:" + pattern + "发生错误!", e);
            return null;
        }
    }
    
    /**
     * 获取系统当前时间
     * 
     * @return 返回字符串
     */
    public static String getNowTimeString()
    {
        SimpleDateFormat df = new SimpleDateFormat(DATE_FULL_STR);
        return df.format(new Date());
    }
    /**
     * 获取系统当前时间
     * @param dateType dateType
     * @return 返回字符串
     */
    public static String getNowDayString(String dateType)
    {
        SimpleDateFormat df = new SimpleDateFormat(dateType);
        return df.format(new Date());
    }
    
    /**
     * 获取系统当前时间
     * 
     * @return Date
     */
    public static Date getNowDateTime()
    {
        return new Date();
    }
    
    /**
     * 获取当前系统时间
     * @return Timestamp
     */
    public static Timestamp getNowTimestamp()
    {
        return new Timestamp(System.currentTimeMillis());
    }
    
    /**
     * 获取系统当前时间
     * @param type 格式化类型
     * @return 返回字符串
     */
    public static String getNowTimeString(String type)
    {
        SimpleDateFormat df = new SimpleDateFormat(type);
        return df.format(new Date());
    }
    
    /**
     * 将当前日期转换成Unix时间戳
     * 
     * @return long 时间戳
     */
    public static long dateToUnixTimestamp()
    {
        long timestamp = new Date().getTime();
        return timestamp;
    }
    
    /**
     * 将日期转换成字符串
     * @param date 日期
     * @param type 格式
     * @return String
     */
    public static String dateToString(Date date,String type)
    {
        SimpleDateFormat formatter = new SimpleDateFormat(type);
        String dateString = "";
        if (date != null)
        {
            dateString = formatter.format(date);
        }
        return dateString;
    }
    
    /**
     * 日期转字符串
     * @param millis 毫秒
     * @param type 格式化
     * @return String
     */
    public static String dateToString(long millis, String type)
    {
        java.util.Date date = new java.util.Date(millis);
        return DateUtil.dateToString(date, type);
    }
    
    /**
     * 获取日期差,返回相差小时数
     * @param nowDate 当前日期
     * @param oldDate 之前日期
     * @return long
     * @throws Exception Exception
     */
    public static long getCompareHour(Date nowDate, Date oldDate) throws Exception
    {
        long d = 0;
        try
        {
            long day = nowDate.getTime() - oldDate.getTime();
            d = day / (60 * 60 * 1000);
        }
        catch (Exception e)
        {
            throw e;
        }
        return d;
    }
    
    /**
     * 判断日期是否为白天
     * 
     * @param catchTime
     *            日期
     * @return true/false
     */
    public static boolean isDaytime(Date catchTime)
    {
        String hm = DateUtil.dateToString(catchTime, "HH:mm");
        int rtn1 = hm.compareTo(DAYTIME_FROM);
        int rtn2 = hm.compareTo(DAYTIME_TO);
        return (rtn1 >= 0 && rtn2 <= 0) ? true : false;
    }
    
    /**
     * 字符串日期转日期
     * @param basicDate 基础日期
     * @param dataFormat 日期格式化
     * @return Date
     * @throws ParseException ParseException
     */
    public static Date parseDateString(String basicDate, String dataFormat) throws ParseException
    {
        if (basicDate == null || basicDate.trim().equals("") || "null".equalsIgnoreCase(basicDate))
        {
            return null;
        }
        SimpleDateFormat df = new SimpleDateFormat(dataFormat);
        Date date = df.parse(basicDate);
        return date;
    }
    
    /**
     * 获取毫秒日期
     * @param millisecond 毫秒
     * @return String
     */
    public static String getByMillisecond(long millisecond)
    {
        long hour = 0;
        long minute = 0;
        long second = 0;
        second = millisecond / 1000;
        if (second >= 3600)
        {
            hour = second / 3600;
            second -= hour * 3600;
        }
        if (second >= 60)
        {
            minute = second / 60;
            second -= minute * 60;
        }
        StringBuilder timeBuilder = new StringBuilder();
        
        timeBuilder.append(hour).append("-");
        
        timeBuilder.append(minute);
        
        return timeBuilder.toString();
    }
    
    /**
     * 输出时间差
     * @param startTime 开始时间
     * @param endTime 结束时间
     * @return String
     */
    public static String dateDiff(Date startTime, Date endTime)
    {
        // 按照传入的格式生成一个simpledateformate对象
        // SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        long nd = 1000 * 24 * 60 * 60;// 一天的毫秒数
        long nh = 1000 * 60 * 60;// 一小时的毫秒数
        long nm = 1000 * 60;// 一分钟的毫秒数
        //long ns = 1000;// 一秒钟的毫秒数
        long diff;
        long day = 0;
        long hour = 0;
        long min = 0;
        //long sec = 0;
        // 获得两个时间的毫秒时间差异
        
        diff = endTime.getTime() - startTime.getTime();
        day = diff / nd;// 计算差多少天
        hour = diff % nd / nh + day * 24;// 计算差多少小时
        min = diff % nd % nh / nm + day * 24 * 60;// 计算差多少分钟
        //sec = diff % nd % nh % nm / ns;// 计算差多少秒
        // 输出结果
        String str = day + "天" + (hour - day * 24) + "小时" + (min - day * 24 * 60) + "分钟";
        
        return str;
    }
    
    /**
     * 获取给定日期提前second秒的日期
     * @param date 日期
     * @param second 秒
     * @return time
     */
    public static Date predate(Date date,int second)
    {
        Calendar c = new GregorianCalendar();
        c.setTime(date);//设置参数时间
        c.add(Calendar.SECOND,-second);//前30秒
        date = c.getTime(); 
        return date;
    }
    /**
     * 获取给定日期延后second秒的日期
     * @param date 日期
     * @param second 秒
     * @return time
     */
    public static Date delayTime(Date date,int second)
    {
        Calendar c = new GregorianCalendar();
        c.setTime(date);//设置参数时间
        c.add(Calendar.SECOND,second);//前30秒
        date = c.getTime(); 
        return date;
    }
    /**
     * 获取几天前的日期
     * @param d 当前日期
     * @param day 天数
     * @return Date
     */
    public static Date getDateBefore(Date d, int day) 
    {  
        Calendar now = Calendar.getInstance();  
        now.setTime(d);  
        now.set(Calendar.DATE, now.get(Calendar.DATE) - day);  
        return now.getTime();  
    }   
    /**
     * 获取几天后的日期
     * @param d 当前日期
     * @param day 天数
     * @return Date
     */
    public static Date getDateAfter(Date d, int day) 
    {  
        Calendar now = Calendar.getInstance();  
        now.setTime(d);  
        now.set(Calendar.DATE, now.get(Calendar.DATE) + day);  
        return now.getTime();  
    }   
    /** 
     *  
     * 描述:获取上个月的最后一天. 
     *  
     * @return String
     */  
    public static String getLastMaxMonthDate() 
    {  
        SimpleDateFormat dft = new SimpleDateFormat("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());  
    }  
    /** 
     * 获取当前月份最后一天 
     *  
     * @return String
     */  
    public static String getMaxMonthDate()
    {  
        SimpleDateFormat dft = new SimpleDateFormat("dd");  
        Calendar calendar = Calendar.getInstance();  
        calendar.setTime(new Date());  
        calendar.set(Calendar.DAY_OF_MONTH, calendar.getActualMaximum(Calendar.DAY_OF_MONTH));  
        return dft.format(calendar.getTime());  
    }  
    /** 
     * 获取上一个月 
     *  
     * @return String
     */  
    public static String getLastMonth() 
    {  
        Calendar cal = Calendar.getInstance();  
        cal.add(Calendar.MONTH, -1);  
        SimpleDateFormat dft = new SimpleDateFormat("yyyy-MM");  
        return dft.format(cal.getTime());  
    }  

    /**
     * 输出时间差
     * @param startDate 开始时间
     * @param endDate 结束时间
     * @return String
     */
    public static long diffDay(String startDate, String endDate)
    {
        Date startTime = parse(startDate);
        Date endTime = parse(endDate);
        long nd = 1000 * 24 * 60 * 60;// 一天的毫秒数
        long diff;
        long day = 0;
        // 获得两个时间的毫秒时间差异
        
        diff = endTime.getTime() - startTime.getTime();
        day = diff / nd;// 计算差多少天
        return day;
    }
    
    /**
     * @param currentYear 当前所在的年份
     * @param currentMonth 当前所在的月份
     * @return 横坐标
     */
    public static String[] generateXaxis(Integer currentYear, Integer currentMonth)
    {
        Integer prevYear  = currentYear -1 ;
        String[] xAxis = new String[12];
        int subIndex = 0;
        for (int i = currentMonth+1 ; i < 13; i++)
        {
            StringBuffer sb = new StringBuffer();
            sb.append(String.valueOf(prevYear));
            sb.append("-");
            sb.append(DateUtil.preApped(2,i));
            xAxis[subIndex] = sb.toString();
            subIndex++;
        }
        for (int i = 1; i < currentMonth+1; i++)
        {
            StringBuffer sb = new StringBuffer();
            sb.append(String.valueOf(currentYear));
            sb.append("-");
            sb.append(DateUtil.preApped(2,i));
            xAxis[subIndex] = sb.toString();
            subIndex++;
        }
        return xAxis;    
    }
    
    /**
     * 
     * @param totalCount 总长度  如果是100 就是3
     * @param number 需要在前面补零的数字
     * @return 补零后的字符串数字
     * 关于 Stringbuffer 拼接的字符串
     *  0 代表前面补充0
     *  3 代表长度为3
     *  d 代表参数为正数型           
     */
    public static  String preApped(Integer  totalCount,Integer number)
    {
        if (null != totalCount && null != number)
        {
            StringBuffer sb =  new StringBuffer();
            sb.append("%0");
            sb.append(totalCount);
            sb.append("d");
            return String.format(sb.toString(), number);
        }
        else
        {
            return "";
        }    
    }
    /**
     * 获取七天前的日期
     * 假设今天2018年10月17号  返回2018年10月11号
     * @return 一周前的日期
     */
    public static String queryTheDayBeforeSeven()
    {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        Calendar c = Calendar.getInstance();
        //过去七天
        c.setTime(new Date());
        c.add(Calendar.DATE, - 6);
        Date d = c.getTime();
        String day = format.format(d);
        return day;
    }
    
    /**
     * 获取给定日期后hour小时的日期
     * @param date 日期
     * @param hour 小时
     * @return time
     */
    public static Date backHeadDate(Date date,int hour)
    {
        Calendar c = new GregorianCalendar();
        c.setTime(date);//设置参数时间
        c.add(Calendar.HOUR_OF_DAY,hour);//前1小时
        date = c.getTime(); 
        return date;
    }
    
    /**
     * 获取给定日期提前hour小时的日期
     * @param date 日期
     * @param hour 小时
     * @return time
     */
    public static Date frontHeadDate(Date date,int hour)
    {
        Calendar c = new GregorianCalendar();
        c.setTime(date);//设置参数时间
        c.add(Calendar.HOUR_OF_DAY,-hour);//前1小时
        date = c.getTime(); 
        return date;
    }

	  /**
     * 日期转化为毫秒
     * @param date 日期
     * @return
     */
    public static long switchMsec(Date date)
    {
    	try {
    		Calendar calendar=Calendar.getInstance();
        	calendar.setTime(date);
        	long timeInMillis = calendar.getTimeInMillis();
        	return timeInMillis;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return 0;	
    }
    
    /**
     * 毫秒转化为日期字符串
     * @param msec 毫秒
     * @return
     */
    public static String switchDate(long msec)
    {
    	try {
    		Date date=new Date();
    		date.setTime(msec);
    		String format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(date);
    		return format;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
    }

	/**
     * @MethodName:  isEffectiveDate  
     * @Description: 判断时间是否在某个时间段内
     * @param        nowTime 判断的时间
     * @param        startTime 开始时间
     * @param        endTime 结束时间
     * @return       boolean
     */
    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;
        }
    }
}

文章仅用来作记录分享,以上纯属个人见解,如有不当之处,还望指正。

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

程序猿爱篮球

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值