java日期/时间转换工具类

package com.sdream.chess.db.utils;

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


public class DatetimeUtils {

	public static final String DEFAULT_TIME_FORMAT = "HH:mm:ss";
	
    public static final String DEFAULT_DATE_FORMAT = "yyyy-MM-dd";

    public static final String DEFAULT_DATE_TIME_FORMAT = "yyyy-MM-dd HH:mm:ss";
    public static final String DEFAULT_DATE_TIME_FORMAT1=  "yyyyMMddHHmmss";


    private static final Calendar calendar = Calendar.getInstance();
    
    private static SimpleDateFormat sdf = null;
    
    public static String formatDate1() {
        return format(new Date(), DEFAULT_DATE_TIME_FORMAT1, DEFAULT_DATE_TIME_FORMAT1);
    }
    //每天的秒数
    public static final long SECONDS = 24 * 60 * 60 ;
    
    /**
     * 按照默认格式参数(yyyy-MM-dd)格式化日期
     *
     * @param date
     * @param format
     * @return
     */
    public static String formatDate(Date date) {
        return formatDate(date, null);
    }
    
    /**
     * 按照默认格式参数(HH:mm:ss)格式化时间
     * @author lt3
     * @date 2013-11-26
     * @param date
     * @return
     */
    public static String formatTime(Date date) {
    	 sdf = new SimpleDateFormat(DEFAULT_TIME_FORMAT);
    	 String time = sdf.format(date);
        return time;
    }
    
    /**
     * 按照指定格式参数格式化时间
     * @author lt3
     * @date 2013-11-26
     * @param date
     * @return
     */
    public static String formatTime(Date date, String format) {
    	 sdf = new SimpleDateFormat(format);
    	 String time = sdf.format(date);
        return time;
    }

    /**
     * 按照默认格式参数(yyyy-MM-dd HH:mm:ss)格式化时间
     *
     * @param date
     * @param format
     * @return
     */
    public static String formatDatetime(Date date) {
        return formatDatetime(date, null);
    }

    /**
     * 按照指定的格式参数格式化日期,如果格式参数为空,那么采用默认格式参数(yyyy-MM-dd)
     *
     * @param date
     * @param format
     * @return
     */
    public static String formatDate(Date date, String format) {
        return format(date, format, DEFAULT_DATE_FORMAT);
    }

    /**
     * 按照指定的格式参数格式化时间,如果格式参数为空,那么采用默认格式参数(yyyy-MM-dd HH:mm:ss)
     *
     * @param date
     * @param format
     * @return
     */
    public static String formatDatetime(Date date, String format) {
        return format(date, format, DEFAULT_DATE_TIME_FORMAT);
    }

    /**
     * 根据传入的日期以及月份数计算并返回日期
     *
     * @param date
     * @param months
     * @return
     */
    public static Date addMonth(Date date, int months) {

        calendar.setTime(date);
        calendar.add(Calendar.MONTH, months);

        return calendar.getTime();
    }

    /**
     * 根据传入的日期以及天数计算并返回日期
     *
     * @param date
     * @param hours
     * @return
     */
    public static Date addDate(Date date, int days) {

        calendar.setTime(date);
        calendar.add(Calendar.DATE, days);

        return calendar.getTime();
    }

    /**
     * 根据传入的日期以及分钟数计算并返回日期
     *
     * @param date
     * @param months
     * @return
     */
    public static Date addMinute(Date date, int minutes) {

        calendar.setTime(date);
        calendar.add(Calendar.MINUTE, minutes);

        return calendar.getTime();
    }

    /**
     * 根据传入的日期以及秒数计算并返回日期
     *
     * @param date
     * @param seconds
     * @return
     */
    public static Date addSecond(Date date, int seconds) {

        calendar.setTime(date);
        calendar.add(Calendar.SECOND, seconds);

        return calendar.getTime();
    }
    /**
     * 根据传入的日期以及小时数计算并返回日期
     *
     * @param date
     * @param hours
     * @return
     */
    public static Date addHour(Date date, int hours) {

        calendar.setTime(date);
        calendar.add(Calendar.HOUR, hours);

        return calendar.getTime();
    }

    /**
     * 根据传入的日期以及年数计算并返回日期
     *
     * @param date
     * @param years
     * @return
     */
    public static Date addYear(Date date, int years) {

        calendar.setTime(date);
        calendar.add(Calendar.YEAR, years);

        return calendar.getTime();
    }

    /**
     * 根据传入的日期时间字符串生成日期对象
     * 传入的日期字符串格式为 yyyy-MM-dd hh:mm:ss
     * 如果hh:mm:ss没有设置,默认为00:00:00
     *
     * @param str
     * @return
     */
    public static Date parseDateByStr(String str) {

        if (str == null)
            return null;

        String dateArray[] = str.split("-");
        if (dateArray.length != 3) 
            return null;

        int year = Integer.parseInt(dateArray[0]);
        int month = Integer.parseInt(dateArray[1]);
        int date = 1;
        int hour = 0;
        int minute = 0;
        int second = 0;

        if (dateArray[2].indexOf(":") > 0) {
            int i = dateArray[2].indexOf(" ");
            date = Integer.parseInt(dateArray[2].substring(0, i));
            if (i > 0) {
                String hmStr = dateArray[2].substring(i + 1);
                String[] hmArray = hmStr.split(":");
                if (hmArray.length >= 2) {
                    hour = Integer.parseInt(hmArray[0]);
                    minute = Integer.parseInt(hmArray[1]);
                    if (hmArray.length == 3)
                        second = Integer.parseInt(hmArray[2]);
                }
            }
        } else {
            date = Integer.parseInt(dateArray[2]);
        }
        
        calendar.set(year, month - 1, date, hour, minute, second);
        return calendar.getTime();
    }

    /**
     * 返回d2 - d1的秒数
     *
     * @param d1
     * @param d2
     * @return
     */
    public static long secondDiffWith(Date d1, Date d2) {
        long timeMills = d2.getTime() - d1.getTime();
        return timeMills / (1000);
    }
    /**
     * 返回d2 - d1 的毫秒数
     * @param d1
     * @param d2
     * @return
     */
    public static long millisecondDiffWith(Date d1, Date d2){
    	long timeMills = d2.getTime() - d1.getTime();
        return timeMills;
    }
    /**
     * 返回d2 - d1的分数
     *
     * @param d1
     * @param d2
     * @return
     */
    public static long minuteDiffWith(Date d1, Date d2) {
        long timeMills = d2.getTime() - d1.getTime();
        return timeMills / (1000 * 60);
    }
    /**
     * 返回d2 - d1的小时数
     * @param d1
     * @param d2
     * @return
     */
    public static long hourDiffWith(Date d1, Date d2) {
        long timeMills = d2.getTime() - d1.getTime();
        return timeMills / (1000 * 60 * 60);
    }
    /**
     * 返回d2 - d1的天数
     *
     * @param d1
     * @param d2
     * @return
     */
    public static long dateDiffWith(Date d1, Date d2) {
        long timeMills = d2.getTime() - d1.getTime();
        return timeMills / (1000 * 60 * 60 * 24);
    }
    /**
     * 返回d2 - d1的月数
     *
     * @param d1
     * @param d2
     * @return
     */
    public static long monthDiffWith(Date d1, Date d2) {
        long timeMills = d2.getTime() - d1.getTime();
        return timeMills / (1000 * 60 * 60 * 24*30);
    }
    /**
     * 按照默认的格式(yyyy-MM-dd)比较两个日期
     *
     * @param date1
     * @param date2
     * @return 0-date1 == date2;
* 小于0-date1 < date2;
* 大于0-date1 > date2 */ public static int compareDate(Date date1, Date date2) { return compareDate(date1, date2, DEFAULT_DATE_FORMAT); } /** * 按照指定的格式比较两个日期 * * @param date1 * @param date2 * @param format 将两个日期转化为什么格式后比较 * @return 0-date1 == date2;
* 小于0-date1 < date2;
* 大于0-date1 > date2 */ public static int compareDate(Date date1, Date date2, String format) { String date = DatetimeUtils.formatDate(date1, format); return date.compareTo(DatetimeUtils.formatDate(date2, format)); } /** * 按照指定的格式比较两个日期 * @author lt3 * @date 2013-11-15 * @param compareDate 比较的时间 * @param comparedDate 待比较的时间 * @return 0-compareDate == comparedDate;
* 小于0-compareDate < comparedDate;
* 大于0-compareDate > comparedDate */ public static int compareDate(String compareDate, String comparedDate) { long minusResult = 0; try { SimpleDateFormat sdf = new SimpleDateFormat(DEFAULT_DATE_TIME_FORMAT); long compareDateMillionSeconds = sdf.parse(compareDate).getTime(); long comparedDateMillionSeconds = sdf.parse(comparedDate).getTime(); minusResult = compareDateMillionSeconds - comparedDateMillionSeconds; } catch (ParseException e) { // TODO Auto-generated catch block e.printStackTrace(); } return minusResult > 0 ? 1 : minusResult < 0 ? -1 : 0; } /** * 按格式条件,格式化字符串时间值 */ public static Date parseStr2Date(String dateStr, String formate) { return parse(dateStr, formate, DEFAULT_DATE_TIME_FORMAT); } /** * 按默认格式,格式化字符串时间值 */ public static Date parseStr2Date(String dateStr) { return parseStr2Date(dateStr, null); } /** * 获得当某日期减去天数后的日期,对days有限制 * * @author zhangxr * @date 2009-1-12 * @decsript 某日期减去天数后的日期 * @param firthDate 某一日期 * @param days 天数 * @return date */ public static Date getDateByDecDays(Date firthDate, int days) { long myTime = (firthDate.getTime() / 1000) - 60 * 60 * 24 * days; firthDate.setTime(myTime * 1000); return firthDate; } public static Date getDateByAddDays(Date firthDate, int days) { long myTime = (firthDate.getTime() / 1000) + 60 * 60 * 24 * days; firthDate.setTime(myTime * 1000); return firthDate; } /*---------------------------- private methods -------------------------*/ /*** * 格式化Date对象 * * @param date * @param format * @param defaultFormat 当format为空时采用该格式参数格式化Date对象 * @return */ private static String format(Date date, String format, String defaultFormat) { if (format == null || format.trim().length() == 0) format = defaultFormat; SimpleDateFormat dateFormat = new SimpleDateFormat(format); return dateFormat.format(date); } /** * 添加时间转换 * @author zhangxr * @date 2009-1-7 * @decsript 将字符格式的时间值转换成真正的时间格式 * @param dateStr 字符串时间值 * @param format 格式 * @param defaultFormat 默认时间格式 * @return */ private static Date parse(String dateStr, String format, String defaultFormat) { Date tmpDate = null ; if(null==format || "".equals(format)){ format = defaultFormat ; } SimpleDateFormat sDateFormat = new SimpleDateFormat(format); try { tmpDate = sDateFormat.parse(dateStr); } catch(ParseException ex) { throw new RuntimeException("时间格式不正确!") ; } return tmpDate ; } public static int getYear(java.util.Date date) { java.util.Calendar c = java.util.Calendar.getInstance(); c.setTime(date); return c.get(java.util.Calendar.YEAR); } public static int getMonth(java.util.Date date) { java.util.Calendar c = java.util.Calendar.getInstance(); c.setTime(date); return c.get(java.util.Calendar.MONTH)+1; } public static int getDate(java.util.Date date) { java.util.Calendar c = java.util.Calendar.getInstance(); c.setTime(date); return c.get(java.util.Calendar.DATE); } public static Date stringToDate(String date, String partten) { Date dateResult = new Date(); if (date != null) { SimpleDateFormat myFmt = new SimpleDateFormat(partten); try { dateResult = myFmt.parse(date); } catch (ParseException e) { e.printStackTrace(); } } return dateResult; } public static Date dateToDate(Date date) { int year = getYear(date); int month = getMonth(date); int day = getDate(date); String dateStr = String.valueOf(year)+"-"+String.valueOf(month)+"-"+String.valueOf(day); System.out.println(dateStr); Date dateResult = stringToDate(dateStr,"yyyy-MM-dd"); System.out.println(dateResult); return dateResult; } /** * 根据星期(周的第n天)、时间、分、秒返回日期 */ public static Date parseDate(int week,int hour,int minute,int second) { Calendar currentCal = Calendar.getInstance(); long currentTime = currentCal.getTimeInMillis(); Calendar c2 = Calendar.getInstance(); c2.set(Calendar.DAY_OF_WEEK, week); c2.set(Calendar.HOUR_OF_DAY, hour); c2.set(Calendar.MINUTE, minute); c2.set(Calendar.SECOND, second); if(c2.getTimeInMillis()>currentTime){ return c2.getTime(); }else{ c2.add(Calendar.DATE, 7); return c2.getTime(); } } /** * 获取中国习惯用的星期 * @author zhangwh * @date 2019-3-12 * 1:星期一; 2: 星期二; 3:星期三; 4:星期四; 5:星期五; 6:星期六 7: 星期日; */ public static int getChinaDay(Date date){ Date d = new Date(); if(null != date){ d = date; } calendar.setTime(d); int day = calendar.get(Calendar.DAY_OF_WEEK); if(day==1){ day=7; }else{ day-=1; } return day; } /** * 获取中国习惯用的星期 * @author zhangwh * @date 2019-3-12 * 1:星期一; 2: 星期二; 3:星期三; 4:星期四; 5:星期五; 6:星期六 7: 星期日; */ public static int getChinaDay(){ calendar.setTime(new Date()); int day = calendar.get(Calendar.DAY_OF_WEEK); if(day==1){ day=7; }else{ day-=1; } return day; } /** * 获取当前星期 * @author lt3 * @date 2013-11-15 * 1: 星期日; 2:星期一; 3: 星期二; 4:星期三; 5:星期四; 6:星期五; 7:星期六 */ public static int getDay(){ Date d = new Date(); calendar.setTime(d); int day = calendar.get(Calendar.DAY_OF_WEEK); return day; } /** * 获取当前星期 * @param date 为null, 表示当的日期 * @author lt3 * @date 2013-11-15 * 1: 星期日; 2:星期一; 3: 星期二; 4:星期三; 5:星期四; 6:星期五; 7:星期六 */ public static int getDayByDate(Date date){ Date d = new Date(); if(null != date){ d = date; } calendar.setTime(d); int day = calendar.get(Calendar.DAY_OF_WEEK); return day; } /*** 得到本周周一日期* */ public static String getWeekMonday(){ SimpleDateFormat formater=new SimpleDateFormat("yyyy-MM-dd"); Calendar cal = new GregorianCalendar(); cal.setFirstDayOfWeek(Calendar.MONDAY); cal.setTime(new Date()); cal.set(Calendar.DAY_OF_WEEK, cal.getFirstDayOfWeek()); Date first=cal.getTime(); return formater.format(first); } /*** 获得指定时间距离当天结束所剩的秒数 */ public static long getRemainSecondsOneDay(Date currentDate) { Calendar midnight = Calendar.getInstance(); midnight.setTime(currentDate); midnight.add(Calendar.DAY_OF_MONTH, 1); midnight.set(Calendar.HOUR_OF_DAY, 0); midnight.set(Calendar.MINUTE, 0); midnight.set(Calendar.SECOND, 0); midnight.set(Calendar.MILLISECOND, 0); long seconds = ((midnight.getTime().getTime() - currentDate .getTime()) / 1000); return seconds; } /** * 判断是否是当天24小时内时间 * @param inputJudgeDate * @return */ public static boolean isToday(Date inputJudgeDate) { boolean flag = false; //获取当前系统时间 long longDate = System.currentTimeMillis(); Date nowDate = new Date(longDate); SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); String format = dateFormat.format(nowDate); String subDate = format.substring(0, 10); //定义每天的24h时间范围 String beginTime = subDate + " 00:00:00"; String endTime = subDate + " 23:59:59"; Date paseBeginTime = null; Date paseEndTime = null; try { paseBeginTime = dateFormat.parse(beginTime); paseEndTime = dateFormat.parse(endTime); } catch (ParseException e) { e.printStackTrace(); } if(inputJudgeDate.after(paseBeginTime) && inputJudgeDate.before(paseEndTime)) { flag = true; } return flag; } }

 

你可能感兴趣的:(java日期/时间转换工具类)