java 日期工具类

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java 日期工具类相关的知识,希望对你有一定的参考价值。

/**
 * <h3>Class description</h3>
 * <h4>日期处理类</h4>
 *
 * <h4>Special Notes</h4>
 * 
 *
 * @ver 0.1
 * @author terry.wei
 * 2011-5-4
 */
import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.Locale;

import org.jfree.util.Log;

import com.opensymphony.xwork2.ActionContext;

public class DateUtil {
    /**
     * 一天中的天数
     */
    public static long millionSecondsOfDay = 86400000;

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

    public final static String YYMMDD24HHMMSSSSS = "yyMMddHHmmssSSS";

    /**
     * 得到两个日期之间的天数,两头不算,取出数据后,可以根据需要再加
     * 
     * @author Vincent
     * @param date1
     * @param date2
     * @return
     */
    public static int getDay(Date date1, Date date2) {
        Long d2 = date2.getTime();
        Long d1 = date1.getTime();
        return (int) ((d2 - d1) / millionSecondsOfDay);
    }

    /**
     * 计算日期加天数
     * 
     * @author Vincent
     * @param date
     * @param days
     * @return
     */
    public static Date addDay(Date date, int days) {
        Calendar c = new GregorianCalendar();
        c.setTime(date);
        c.add(Calendar.DAY_OF_MONTH, days);
        return c.getTime();
    }

    /**
     * 根据指定日期格式格式化日期
     * 
     * @author Vincent
     * @param date
     * @param formater
     * @return
     */
    public static String format(Date date, String formater) {
        SimpleDateFormat sdf = new SimpleDateFormat(formater);
        return sdf.format(date);
    }

    /**
     * 格式化日期
     * 
     * @author Vincent
     * @param date
     * @param formater
     * @return
     */
    public static Date parse(String date, String formater) {
        SimpleDateFormat sdf = new SimpleDateFormat(formater);
        Date result = null;
        try {
            result = sdf.parse(date);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 根据日期取出是星期几
     * 
     * @author Vincent
     * @param date
     *            Date
     * @return int 返回1-7
     */
    public static int getWeekOfDate(Date date) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        return (calendar.get(Calendar.DAY_OF_WEEK) - 1) == 0 ? 7 : calendar.get(Calendar.DAY_OF_WEEK) - 1;
    }

    /**
     * format "yyyy-MM-dd HH:mm:ss"
     */
    public static String dateToString(Date date, String format) {
        if (date == null)
            return null;
        SimpleDateFormat formatter = new SimpleDateFormat(format);
        return formatter.format(date).trim();

    }

    /**
     * 取Java虚拟机系统时间, 下一天时间
     * 
     * @return 只返回String格式的日期,YYYY-MM-DD, 长10位
     */
    public static String getSysStringDateNext(Date date) {
        Calendar cl = Calendar.getInstance();
        cl.setTime(date);
        cl.add(Calendar.DATE, 1);
        String monthValue = "";
        String dateValue = "";
        if (cl.get(Calendar.MONTH) + 1 < 10) {
            monthValue = "0" + (cl.get(Calendar.MONTH) + 1);
        } else {
            monthValue = String.valueOf(cl.get(Calendar.MONTH) + 1);
        }

        if (cl.get(Calendar.DATE) < 10) {
            dateValue = "0" + (cl.get(Calendar.DATE));
        } else {
            dateValue = String.valueOf(cl.get(Calendar.DATE));
        }
        return cl.get(Calendar.YEAR) + "-" + monthValue + "-" + dateValue;
    }

    /**
     * 取Java虚拟机系统时间, 上一月
     * 
     * @return 只返回String格式的日期,YYYY-MM-DD, 长10位
     */
    public static String getSysStringDateNext() {
        Calendar cl = Calendar.getInstance();
        cl.setTime(new Date());
        String monthValue = "";
        if (cl.get(Calendar.MONTH) + 2 < 10) {
            monthValue = "0" + (cl.get(Calendar.MONTH) + 2);
        } else {
            monthValue = String.valueOf(cl.get(Calendar.MONTH) + 2);
        }
        return cl.get(Calendar.YEAR) + "-" + monthValue + "-" + 01;
    }

    /**
     * 取Java虚拟机系统时间, 上一月
     * 
     * @return 只返回String格式的日期,YYYY-MM-DD, 长10位
     */
    public static String getSysStringDateNextByDate(Date date) {
        Calendar cl = Calendar.getInstance();
        cl.setTime(date);
        String monthValue = "";
        if (cl.get(Calendar.MONTH) + 2 < 10) {
            monthValue = "0" + (cl.get(Calendar.MONTH) + 2);
        } else {
            monthValue = String.valueOf(cl.get(Calendar.MONTH) + 2);
        }
        return cl.get(Calendar.YEAR) + "-" + monthValue + "-" + 01;
    }

    /**
     * 取Java虚拟机系统时间, 当天月
     * 
     * @param selectMonthDate
     * 
     * @return 只返回String格式的日期,YYYY-MM-DD, 长10位
     */
    public static String getSysStringTodayDate(Date selectMonthDate) {
        Calendar cl = Calendar.getInstance();
        cl.setTime(selectMonthDate);
        String monthValue = "";
        if (cl.get(Calendar.MONTH) + 1 < 10) {
            monthValue = "0" + (cl.get(Calendar.MONTH) + 1);
        } else {
            monthValue = String.valueOf(cl.get(Calendar.MONTH) + 1);
        }
        return cl.get(Calendar.YEAR) + "-" + monthValue + "-" + 01;
    }

    /**
     * 取Java虚拟机系统时间, 前一月
     * 
     * @param selectMonthDate
     * 
     * @return 只返回String格式的日期,YYYY-MM-DD, 长10位
     */
    public static String getSysStringDateBack(Date selectMonthDate) {
        Calendar cl = Calendar.getInstance();
        cl.setTime(selectMonthDate);
        String monthValue = "";
        if (cl.get(Calendar.MONTH) < 10) {
            monthValue = "0" + (cl.get(Calendar.MONTH));
        } else {
            monthValue = String.valueOf(cl.get(Calendar.MONTH));
        }
        return cl.get(Calendar.YEAR) + "-" + monthValue + "-" + 01;
    }

    /**
     * 取Java虚拟机系统时间, 返回当前时间戳
     * 
     * @return Timestamp类型的时间
     */
    public static Timestamp getSysTimestamp() {
        return new Timestamp(System.currentTimeMillis());
    }

    private static String getDate(Date date, int dif) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.add(Calendar.DATE, dif);
        String monthValue;
        String dateValue;
        if (calendar.get(Calendar.MONTH) + 1 < 10) {
            monthValue = "0" + (calendar.get(Calendar.MONTH) + 1);
        } else {
            monthValue = String.valueOf(calendar.get(Calendar.MONTH) + 1);
        }
        if (calendar.get(Calendar.DATE) < 10) {
            dateValue = "0" + (calendar.get(Calendar.DATE));
        } else {
            dateValue = String.valueOf(calendar.get(Calendar.DATE));
        }
        return calendar.get(Calendar.YEAR) + "-" + monthValue + "-" + dateValue;
    }

    /**
     * 取Java虚拟机系统时间, 下一天时间
     * 
     * @return 只返回String格式的日期,YYYY-MM-DD, 长10位
     */
    public static String getSysStringDateNextByDate(String strDate) {
        Calendar cl = Calendar.getInstance();
        cl.setTime(DateUtil.parse(strDate, "yyyy-MM-dd"));
        cl.add(Calendar.DATE, 1);
        String monthValue = "";
        String dateValue = "";
        if (cl.get(Calendar.MONTH) + 1 < 10) {
            monthValue = "0" + (cl.get(Calendar.MONTH) + 1);
        } else {
            monthValue = String.valueOf(cl.get(Calendar.MONTH) + 1);
        }

        if (cl.get(Calendar.DATE) < 10) {
            dateValue = "0" + (cl.get(Calendar.DATE));
        } else {
            dateValue = String.valueOf(cl.get(Calendar.DATE));
        }
        return cl.get(Calendar.YEAR) + "-" + monthValue + "-" + dateValue;
    }

    /**
     * 取Java虚拟机系统时间, 前一天时间
     * 
     * @return 只返回String格式的日期,YYYY-MM-DD, 长10位
     */
    public static String getSysStringDateBackByDate(String strDate) {
        Calendar cl = Calendar.getInstance();
        cl.setTime(DateUtil.parse(strDate, "yyyy-MM-dd"));
        cl.add(Calendar.DATE, -1);
        String monthValue = "";
        String dateValue = "";
        if (cl.get(Calendar.MONTH) + 1 < 10) {
            monthValue = "0" + (cl.get(Calendar.MONTH) + 1);
        } else {
            monthValue = String.valueOf(cl.get(Calendar.MONTH) + 1);
        }

        if (cl.get(Calendar.DATE) < 10) {
            dateValue = "0" + (cl.get(Calendar.DATE));
        } else {
            dateValue = String.valueOf(cl.get(Calendar.DATE));
        }
        return cl.get(Calendar.YEAR) + "-" + monthValue + "-" + dateValue;
    }

    /**
     * 取Java虚拟机系统时间, 当天时间
     * 
     * @return 只返回String格式的日期,YYYY-MM-DD, 长10位
     */
    public static String getSysStringDateBackByDate() {
        Calendar cl = Calendar.getInstance();
        cl.setTime(new Date());
        String monthValue = "";
        String dateValue = "";
        if (cl.get(Calendar.MONTH) + 1 < 10) {
            monthValue = "0" + (cl.get(Calendar.MONTH) + 1);
        } else {
            monthValue = String.valueOf(cl.get(Calendar.MONTH) + 1);
        }

        if (cl.get(Calendar.DATE) < 10) {
            dateValue = "0" + (cl.get(Calendar.DATE));
        } else {
            dateValue = String.valueOf(cl.get(Calendar.DATE));
        }
        return cl.get(Calendar.YEAR) + "-" + 12 + "-" + 31;
    }

    /**
     * 取Java虚拟机系统时间, 当天时间
     * 
     * @return 只返回String格式的日期,YYYY-MM-DD, 长10位
     */
    public static String getSysStringDate() {
        Calendar cl = Calendar.getInstance();
        cl.setTime(new Date());
        String monthValue = "";
        String dateValue = "";
        if (cl.get(Calendar.MONTH) + 1 < 10) {
            monthValue = "0" + (cl.get(Calendar.MONTH) + 1);
        } else {
            monthValue = String.valueOf(cl.get(Calendar.MONTH) + 1);
        }

        if (cl.get(Calendar.DATE) < 10) {
            dateValue = "0" + (cl.get(Calendar.DATE));
        } else {
            dateValue = String.valueOf(cl.get(Calendar.DATE));
        }
        return cl.get(Calendar.YEAR) + "-" + monthValue + "-" + dateValue;
    }

    /**
     * 取Java虚拟机系统时间, 当天时间 与星期几
     * 
     * @return 只返回String格式的日期,YYYY-MM-DD, 长10位
     */
    public static String getSysStringDateByWeek() {

        Calendar cl = Calendar.getInstance();
        cl.setTime(new Date());
        String monthValue = "";
        String dateValue = "";
        if (cl.get(Calendar.MONTH) + 1 < 10) {
            monthValue = "0" + (cl.get(Calendar.MONTH) + 1);
        } else {
            monthValue = String.valueOf(cl.get(Calendar.MONTH) + 1);
        }

        if (cl.get(Calendar.DATE) < 10) {
            dateValue = "0" + (cl.get(Calendar.DATE));
        } else {
            dateValue = String.valueOf(cl.get(Calendar.DATE));
        }
        String dateString = cl.get(Calendar.YEAR) + "-" + monthValue + "-" + dateValue;
        String weekString = "";
        DateFormat format1 = new SimpleDateFormat("yyyy-MM-dd");

        try {
            weekString = DateUtil.getD(format1.parse(dateString));
        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        return weekString + "        " + dateString;
    }

    /**
     * 获取星期几
     * 
     * @return
     */
    public static String getD(Date d) {
        Locale localLanguage = ActionContext.getContext().getLocale();
        String languageValue = localLanguage.getLanguage();
        java.text.SimpleDateFormat f;
        if (languageValue != null && (languageValue.toUpperCase().indexOf("CN") >= 0 || languageValue.toUpperCase().indexOf("ZH") >= 0 || languageValue.toUpperCase().indexOf("zh_CN") >= 0)) {
            f = new java.text.SimpleDateFormat("EEEE", Locale.SIMPLIFIED_CHINESE);
        } else {
            f = new java.text.SimpleDateFormat("EEEE", Locale.US);
        }

        return f.format(d);
    }

    /**
     * 年月日时分秒
     * 
     * @return
     */
    public static String getSysStringYYYYMMDDHHMMSSDate() {
        Calendar cl = Calendar.getInstance();
        cl.setTime(new Date());
        String monthValue = "";
        String dateValue = "";
        if (cl.get(Calendar.MONTH) + 1 < 10) {
            monthValue = "0" + (cl.get(Calendar.MONTH) + 1);
        } else {
            monthValue = String.valueOf(cl.get(Calendar.MONTH) + 1);
        }

        if (cl.get(Calendar.DATE) < 10) {
            dateValue = "0" + (cl.get(Calendar.DATE));
        } else {
            dateValue = String.valueOf(cl.get(Calendar.DATE));
        }
        return cl.get(Calendar.YEAR) + "-" + monthValue + "-" + dateValue + " " + cl.get(Calendar.HOUR_OF_DAY) + ":" + cl.get(Calendar.MINUTE);
    }

    /**
     * 取Java虚拟机系统时间, 当天时间
     * 
     * @return 只返回String格式的日期,YYYY-MM-DD, 长10位
     */
    public static String getSysStringYear() {
        Calendar cl = Calendar.getInstance();
        cl.setTime(new Date());
        String monthValue = "";
        String dateValue = "";
        if (cl.get(Calendar.MONTH) + 1 < 10) {
            monthValue = "0" + (cl.get(Calendar.MONTH) + 1);
        } else {
            monthValue = String.valueOf(cl.get(Calendar.MONTH) + 1);
        }

        if (cl.get(Calendar.DATE) < 10) {
            dateValue = "0" + (cl.get(Calendar.DATE));
        } else {
            dateValue = String.valueOf(cl.get(Calendar.DATE));
        }
        return cl.get(Calendar.YEAR) + "";
    }

    // ////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    // 获得当前日期与本周一相差的天数
    private static int getMondayPlus(String strDate) {
        Calendar cd = Calendar.getInstance();
        cd.setTime(DateUtil.parse(strDate, "yyyy-MM-dd"));
        // 获得今天是一周的第几天,星期日是第一天,星期二是第二天......
        int dayOfWeek = cd.get(Calendar.DAY_OF_WEEK);
        if (dayOfWeek == 1) {
            return -6;
        } else {
            return 2 - dayOfWeek;
        }
    }

    // 获得上周星期一的日期
    public static String getPreviousMonday(String strDate) {
        int mondayPlus = getMondayPlus(strDate);
        GregorianCalendar currentDate = new GregorianCalendar();
        currentDate.setTime(DateUtil.parse(strDate, "yyyy-MM-dd"));
        currentDate.add(GregorianCalendar.DATE, mondayPlus + 7 * -1);
        Date monday = currentDate.getTime();
        return DateUtil.format(monday, "yyyy-MM-dd");
    }

    // 获得本周星期一的日期
    public static String getCurrentMonday(String strDate) {
        int mondayPlus = getMondayPlus(strDate);
        GregorianCalendar currentDate = new GregorianCalendar();
        currentDate.setTime(DateUtil.parse(strDate, "yyyy-MM-dd"));
        currentDate.add(GregorianCalendar.DATE, mondayPlus);
        Date monday = currentDate.getTime();
        return DateUtil.format(monday, "yyyy-MM-dd");
    }

    // 获得下周星期一的日期
    public static String getNextMonday(String strDate) {
        int mondayPlus = getMondayPlus(strDate);
        GregorianCalendar currentDate = new GregorianCalendar();
        currentDate.setTime(DateUtil.parse(strDate, "yyyy-MM-dd"));
        currentDate.add(GregorianCalendar.DATE, mondayPlus + 7 * 1);
        Date monday = currentDate.getTime();
        return DateUtil.format(monday, "yyyy-MM-dd");
    }

    /**
     * 获取本周周一
     * 
     * @param date
     * @return
     */
    public static String getCurrentWeekMon(Date date) {
        SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
        Calendar calendar = Calendar.getInstance(); // 获取日历
        calendar.setTime(date);
        calendar.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY); // 将日历翻到这周的周一
        return sf.format(calendar.getTime());
    }

    /**
     * 获取本周周日
     * 
     * @param date
     * @return
     */
    public static String getCurrentWeekSun(Date date) {
        Calendar c = Calendar.getInstance();
        c.setTime(date);
        int dayofweek = c.get(Calendar.DAY_OF_WEEK) - 1;
        if (dayofweek == 0)
            dayofweek = 7;
        c.add(Calendar.DATE, -dayofweek + 7);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        return sdf.format(c.getTime());

    }

    /**
     * 获取前一个月的日期
     * 
     * @return 前一个月的日期
     */
    public static String getTodayBeforeMonth() {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        Date currentTime = new Date();// 得到当前系统时间
        long now = currentTime.getTime();// 返回自 1970 年 1 月 1 日 00:00:00 GMT
                                            // 以来此Date 对象表示毫秒数
        currentTime = new Date(now - 86400000 * 24);
        long now1 = currentTime.getTime();
        currentTime = new Date(now1 - 86400000 * 6);
        String current = formatter.format(currentTime);
        return current;
    }

    /**
     * 计算两个时间之差
     * 
     * @param MaxDate
     * @param MinDate
     * @return
     */
    public static String calculateCostTime(Date MaxDate, Date MinDate) {
        String returnValue = "";
        if (MinDate != null && !"".equals(MinDate)) {
            long number = (MaxDate.getTime() - MinDate.getTime()) / 1000;
            if (number >= 0 && number < 60) {
                returnValue = String.valueOf(number) + " seconds";
            } else if (number >= 60 && number < 3600) {
                long minute = number / 60;
                returnValue = String.valueOf(minute) + " minutes";
            } else {
                long allMinute = number / 60;
                int hour = (int) (allMinute / 60);
                long minute = allMinute - (hour * 60);
                String hoursStr = "";
                if (hour <= 1) {
                    hoursStr = " hour ";
                } else {
                    hoursStr = " hours ";
                }
                returnValue = hour + hoursStr + minute + " minutes";
            }

        }

        return returnValue;
    }

    /**
     * 获取下个月的第一天
     * 
     * @param date
     * @return
     */
    public static Date getNextFirstDate(Date date) {

        GregorianCalendar nextFirstDay = new GregorianCalendar(new Integer(format(date, "yyyy")).intValue(), new Integer(format(date, "MM")).intValue() - 1, 1);
        nextFirstDay.add(GregorianCalendar.MONTH, 1);
        return nextFirstDay.getTime();
    }

    /**
     * 该月最后一天(不必管每月多少天了)
     * 
     * @param date
     * @return
     */

    public static Date getLastDay(Date date) {
        GregorianCalendar lastDay = new GregorianCalendar(new Integer(format(date, "yyyy")).intValue(), new Integer(format(date, "MM")).intValue() - 1, 1);
        lastDay.add(GregorianCalendar.MONTH, 1);
        lastDay.add(GregorianCalendar.DATE, -1);
        return lastDay.getTime();
    }

    /**
     * 英國時間轉中國
     * 
     * @param date
     * @return
     */
    public static String formatChinaDate(String englishDate, String englishFormat) {
        SimpleDateFormat sdf = new SimpleDateFormat(englishFormat, Locale.ENGLISH);
        long millionSeconds;
        Date date = null;
        try {
            millionSeconds = sdf.parse(englishDate).getTime();
            date = new Date(millionSeconds);
            sdf = new SimpleDateFormat("yyyy-MM-dd");
        } catch (ParseException e) {
            Log.error(e);
        }
        return sdf.format(date);
    }

    /**
     * 中國時間轉英國
     * 
     * @param date
     * @return
     */
    public static String formatEnglishDate(String chinaDate) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd", Locale.CHINA);
        long millionSeconds;
        Date date = null;
        try {
            millionSeconds = sdf.parse(chinaDate).getTime();
            date = new Date(millionSeconds);
            sdf = new SimpleDateFormat("ddMMMyy", Locale.ENGLISH);
        } catch (ParseException e) {
            Log.error(e);
        }
        return sdf.format(date);
    }

  
}

 

以上是关于java 日期工具类的主要内容,如果未能解决你的问题,请参考以下文章

JAVA 日期工具类的总结

java工具类之实现日期随意跳转

Android Navigation java.language.IllegalStateException 片段类未设置

推荐一个强大的Java开发工具类库!

Java 日期格式化,Java 日期工具类,Java Date工具类

日期工具类 - DateUtil.java