时间处理方法集合 java

时间处理方法集合 java

package com.XXX.utils;

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.List;
import java.util.Locale;

public class MyDateUtil {
	
	private final static String DATE_FORMAT_YYYY = "yyyy";
	private final static String DATE_FORMAT_MM = "MM";
	private final static String DATE_FORMAT_dd = "dd";
	private final static String DATE_FORMAT_YYYY_MM_DD_HH_MM_SS = "yyyy-MM-dd HH:mm:ss";
	private final static String DATE_FORMAT_YYMMDDHHMMSS = "yyMMddHHmmss";
	private final static String DATE_FORMAT_YYYYMMDDHHMMSSSSS = "yyyyMMddHHmmssSSS";
	 
	/**
     * 得到去年:yyyy
     * 例:2018
     * @return
     */
    public static String getLastYear() {
        SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT_YYYY);
        return String.valueOf(Integer.valueOf(sdf.format(new Date()))-1);
    }
    
	/**
     * 得到当前年:yyyy
     * 例:2019
     * @return
     */
    public static String getNowYear() {
        SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT_YYYY);
        return sdf.format(new Date());
    }
    
    /**
     * 得到当前月:MM
     * 例:01
     * @return
     */
    public static String getNowMonth() {
        SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT_MM);
        return sdf.format(new Date());
    }
    
    /**
     * 得到当前日:dd
     * 例:25
     * @return
     */
    public static String getNowDay() {
        SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT_dd);
        return sdf.format(new Date());
    }
    
    
	/**
     * 得到当前时间:yyyy-MM-dd HH:mm:ss
     * 例:2019-01-09 16:10:00
     * @return
     */
    public static String getNowDate() {
        SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT_YYYY_MM_DD_HH_MM_SS);
        return sdf.format(new Date());
    }
    
	 /**
     * 得到当前时间:yyMMddhhmmss
     * 例:181226104457
     * @return
     */
    public static String getYearToSecondString() {
        SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT_YYMMDDHHMMSS);
        return sdf.format(new Date());
    }
    
    /**
     * 得到当前时间:yyyyMMddhhmmssSSS
     * 例:20190301114059123
     * @return
     */
    public static String getYearToMillisecondString() {
        SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT_YYYYMMDDHHMMSSSSS);
        return sdf.format(new Date());
    }
    
    /**
     * 日期转换
     * 例:2018/9/1 0:00:00	转换成	2018-09-01 00:00:00
     * @return
     */
    public static String getConvertDatesFormat(String dateData) {
    	String newDateData = "";
    	if(dateData!=null && !"".equals(dateData.trim())){
    		String dateArray[] = dateData.split(" ")[0].split("/");
            String timeArray[] = dateData.split(" ")[1].split(":");
            
            String yearString = dateArray[0].trim();
            String monthString = dateArray[1].trim();
            String dayString = dateArray[2].trim();
            String hourString = timeArray[0].trim();
            String minuteString = timeArray[1].trim();
            String secondString = timeArray[2].trim();
            
            monthString = monthString.length()<2?("0"+monthString):monthString;
            dayString = dayString.length()<2?("0"+dayString):dayString;
            hourString = hourString.length()<2?("0"+hourString):hourString;
            minuteString = minuteString.length()<2?("0"+minuteString):minuteString;
            secondString = secondString.length()<2?("0"+secondString):secondString;
            
            newDateData = yearString+"-"+monthString+"-"+dayString+" "+hourString+":"+minuteString+":"+secondString;
    	}
    	return newDateData;
    }
    
    /**
	* 日期转换2
	* 例:2019-08-01T00:00:00+08:00	转换成	2019-08-01 00:00:00
     * @return
     */
    public static String getConvertDatesFormat2(String dateData) {
    	String dateStr = "";
		if(dateData!=null && dateData.indexOf("T")>=0 && dateData.indexOf("+")>=0) {
			try {
				DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
				Date date = df.parse(dateData);
				SimpleDateFormat df1 = new SimpleDateFormat ("EEE MMM dd HH:mm:ss Z yyyy", Locale.UK);
			    Date date1 =  df1.parse(date.toString());
			    DateFormat df2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			    dateStr = df2.format(date1);
			} catch (ParseException e) {
				e.printStackTrace();
			}
		}
		return dateStr;
    }
    
    /**
     * 获取前后日期yyyy-MM-dd
     * @param index
     * @return
     */
    public static String getLastOrNextDays(int index) {
    	String dateString = "";
    	
		Calendar calendar = Calendar.getInstance();  
	    calendar.set(Calendar.DAY_OF_YEAR, calendar.get(Calendar.DAY_OF_YEAR) + index);  
	    Date today = calendar.getTime();  
	    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
	    dateString = format.format(today);
	    
		return dateString;
	}
    
    //获取时间段列表
    /**
     * 输出前?天的所有日期	[...,"2019-01-02","2019-01-03",...."今天的日期"]
     * @param days
     * @return
     */
    public static List<List<String>> getDateList(int days) {
    	List<List<String>> dateList = new ArrayList<List<String>>();
    	for(int i=days;i<0;i++){
    		List<String> dateListItem = new ArrayList<String>();
    		
    		String dateBegin = MyDateUtil.getLastOrNextDays(i);
        	String dateEnd = MyDateUtil.getLastOrNextDays(i+1);
        	
        	dateListItem.add(dateBegin);
        	dateListItem.add(dateEnd);
        	dateList.add(dateListItem);
        	
    	}
		return dateList;
	}
    
    /**
     * 获取两个日期之间的所有日期
     * @param startTime	2018-06-28
     * @param endTime	2018-07-28
     * @return ["2018-06-28","2018-06-29",...."2018-07-28"]
     */
    public static List<String> getDateSegment(String startTime, String endTime) {
    	// 返回的日期集合
        List<String> days = new ArrayList<String>();
        
        try {
        	if(startTime.equals(endTime)) {
        		days.add(startTime);
        	}else {
        		DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
                Date start = dateFormat.parse(startTime);
                Date end = dateFormat.parse(endTime);

                Calendar tempStart = Calendar.getInstance();
                tempStart.setTime(start);

                Calendar tempEnd = Calendar.getInstance();
                tempEnd.setTime(end);
                tempEnd.add(Calendar.DATE, +1);// 日期加1(包含结束)
                while (tempStart.before(tempEnd)) {
                    days.add(dateFormat.format(tempStart.getTime()));
                    tempStart.add(Calendar.DAY_OF_YEAR, 1);
                }
        	}

        } catch (ParseException e) {
            e.printStackTrace();
        }

        return days;
    }
    
    /**
     * 获取某个日期的前几天的日期或后几天的日期
     * @param dateStr	2019-01-31
     * @param num	2
     * @return	2019-02-02
     * @throws Exception
     */
    public static String getDateByBeforeOrAfter(String dateStr, int num){
        Calendar c = Calendar.getInstance();
        Date date = null;
        try {
            date = new SimpleDateFormat("yy-MM-dd").parse(dateStr);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        c.setTime(date);
        int day1 = c.get(Calendar.DATE);
        c.set(Calendar.DATE, day1 + num);
 
        String newDate = new SimpleDateFormat("yyyy-MM-dd").format(c.getTime());
        return newDate;
    }
    
    /**
     * 计算指定日期之前或者之后的多少分钟
     * @param date
     * @param minute
     * @return
     */
    public static String getTimeByMinute(String oldTime, int minute) {
    	String newTime = "";
    	SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT_YYYY_MM_DD_HH_MM_SS);
    	try {
    		if(oldTime==null || "".equals(oldTime) || oldTime.length()<10) {
    			return newTime;
    		}
    		if(oldTime.length()==10) {
    			if(minute>=0) {
    				oldTime = oldTime + " 00:00:00";
    			}else {
    				oldTime = oldTime + " 23:59:59";
    			}
    			
    		}
    		
    		Date date = sdf.parse(oldTime);
    		Calendar calendar = Calendar.getInstance();
            calendar.setTime(date);
            calendar.add(Calendar.MINUTE, minute);
            newTime = sdf.format(calendar.getTime());
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			//e.printStackTrace();
			newTime = "";
		}
        
        return newTime;

    }
    
	/**
	 *  计算时差 单位:分钟
	 * @param actualLandingData
	 * @param actualDepartureTime
	 * @return
	 */
	public static String getTimeDifference(String minuendTime, String reductionTime) {
		// TODO Auto-generated method stub
		String timeDifference = "";
		try {
			if(minuendTime!=null && !"".equals(minuendTime) && minuendTime.length()==19 
					&& reductionTime!=null && !"".equals(reductionTime) && reductionTime.length()==19) {
				minuendTime = minuendTime.replaceAll("/", "-");
				reductionTime = reductionTime.replaceAll("/", "-");
				
				SimpleDateFormat simpleFormat = new SimpleDateFormat(DATE_FORMAT_YYYY_MM_DD_HH_MM_SS);
				Date minuendDate = simpleFormat.parse(minuendTime);
				Date reductionDate = simpleFormat.parse(reductionTime);  
			    long minuend = minuendDate.getTime();  
			    long reduction = reductionDate.getTime();  
			    int minutes = (int) ((minuend - reduction) / (1000 * 60));  
			    timeDifference = String.valueOf(minutes);
			}
		    
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			//e.printStackTrace();
			timeDifference = "";
		}  
	    
		return timeDifference;
	}
	
	/**
	 *  计算时差 单位:天
	 * @param actualLandingData
	 * @param actualDepartureTime
	 * @return
	 */
	public static String getTimeDifferenceForByDay(String minuendTime, String reductionTime) {
		// TODO Auto-generated method stub
		String timeDifference = "";
		try {
			if(minuendTime!=null && !"".equals(minuendTime)
					&& reductionTime!=null && !"".equals(reductionTime)) {
				
				minuendTime = minuendTime.length()==10?(minuendTime + " 00:00:00"):minuendTime;
				reductionTime = reductionTime.length()==10?(reductionTime + " 00:00:00"):reductionTime;
				
				minuendTime = minuendTime.replaceAll("/", "-");
				reductionTime = reductionTime.replaceAll("/", "-");
				
				SimpleDateFormat simpleFormat = new SimpleDateFormat(DATE_FORMAT_YYYY_MM_DD_HH_MM_SS);
				Date minuendDate = simpleFormat.parse(minuendTime);
				Date reductionDate = simpleFormat.parse(reductionTime);  
			    long minuend = minuendDate.getTime();  
			    long reduction = reductionDate.getTime();  
			    int day = (int) ((minuend - reduction) / (1000 * 60 * 60 * 24));  
			    timeDifference = String.valueOf(day);
			}
		    
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			//e.printStackTrace();
			timeDifference = "";
		}  
	    
		return timeDifference;
	}

    public static void main(String[] args) {
    	try {
    		System.out.println(getTimeByMinute("2019-04-05 00:50:00", 420-480));
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

    
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值