码迷,mamicode.com
首页 > 其他好文 > 详细

Date工具类

时间:2018-01-09 14:41:13      阅读:152      评论:0      收藏:0      [点我收藏+]

标签:ast   amount   time   sunday   substring   substr   dmi   throws   else   

java 时间工具类

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.TimeZone;
import org.apache.commons.lang3.StringUtils;

public class DateUtils {
    public static final String PATTERN_DATE = "yyyy-MM-dd";
    public static final String PATTERN_DATE2 = "MM-dd";
    public static final String PATTERN_DATETIME = "yyyy-MM-dd HH:mm:ss";
    public static final String PATTERN_DATETIME_IOS8601 = "yyyy-MM-dd‘T‘HH:mm:ss‘Z‘";

    public DateUtils() {
    }

    public static Date date(int year, int month, int day) {
        return date(year, month, day, 0, 0, 0);
    }

    public static Date date(int year, int month, int day, int hour, int minute, int second) {
        Calendar calendar = Calendar.getInstance();
        calendar.setLenient(false);
        calendar.set(year, month, day, hour, minute, second);
        calendar.set(14, 0);
        return calendar.getTime();
    }

    public static Date getOneDayEndTime(Date date) {
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        cal.set(11, 23);
        cal.set(12, 59);
        cal.set(13, 59);
        cal.set(14, 999);
        return cal.getTime();
    }

    public static Date getOneDayEndTimeNoMill(Date date) {
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        cal.set(11, 23);
        cal.set(12, 59);
        cal.set(13, 59);
        return cal.getTime();
    }

    public static String getOneDay(Date date) {
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        cal.set(11, 23);
        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        return dateFormat.format(cal.getTime());
    }

    public static Date getOneDayStartTime(Date date) {
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        cal.set(11, 0);
        cal.set(12, 0);
        cal.set(13, 0);
        cal.set(14, 0);
        return cal.getTime();
    }

    public static Date getOneDayStartTimeNoMill(Date date) {
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        cal.set(11, 0);
        cal.set(12, 0);
        return cal.getTime();
    }

    public static Date parseDate(String string, String pattern) throws ParseException {
        SimpleDateFormat sdf = new SimpleDateFormat(pattern);
        sdf.setLenient(false);
        return sdf.parse(string);
    }

    public static Date parseDate(String string, String pattern, TimeZone timeZone) throws ParseException {
        SimpleDateFormat sdf = new SimpleDateFormat(pattern);
        sdf.setTimeZone(timeZone);
        sdf.setLenient(false);
        return sdf.parse(string);
    }

    public static int getWeekOfDateNum(Date dt) {
        Calendar cal = Calendar.getInstance();
        cal.setTime(dt);
        int w = cal.get(7) - 1;
        if (w < 0) {
            w = 0;
        }

        return w;
    }

    public static String getWeekOfDate(Date dt) {
        String[] weekDays = new String[]{"星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"};
        int w = getWeekOfDateNum(dt);
        return weekDays[w];
    }

    public static String getMondayOfWeek() {
        return getMondayOfWeek(new Date(), "yyyy-MM-dd");
    }

    public static String getMondayOfWeek(Date date, String pattern) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        DateFormat dateFormat = new SimpleDateFormat(pattern);
        calendar.setFirstDayOfWeek(2);
        int dayWeek = calendar.get(7);
        if (1 == dayWeek) {
            calendar.add(5, -1);
        }

        int day = calendar.get(7);
        calendar.add(5, calendar.getFirstDayOfWeek() - day);
        return dateFormat.format(calendar.getTime());
    }

    public static String getSundayOfWeek() {
        return getSundayOfWeek(new Date(), "yyyy-MM-dd");
    }

    public static String getSundayOfWeek(Date date, String pattern) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        DateFormat dateFormat = new SimpleDateFormat(pattern);
        calendar.setFirstDayOfWeek(2);
        int dayWeek = calendar.get(7);
        if (1 == dayWeek) {
            calendar.add(5, -1);
        }

        int day = calendar.get(7);
        calendar.add(5, calendar.getFirstDayOfWeek() - day + 6);
        return dateFormat.format(calendar.getTime());
    }

    public static String getFirstDayOfMonth() {
        Calendar calendar = Calendar.getInstance();
        calendar.set(5, 1);
        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        return dateFormat.format(calendar.getTime());
    }

    public static String getFirstDayOfMonth(Date date, String pattern) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.set(5, 1);
        DateFormat dateFormat = new SimpleDateFormat(pattern);
        return dateFormat.format(calendar.getTime());
    }

    public static String getLastDayOfMonth() {
        Calendar calendar = Calendar.getInstance();
        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        calendar.set(5, 1);
        calendar.roll(5, -1);
        return dateFormat.format(calendar.getTime());
    }

    public static String getLastDayOfMonth(Date date, String pattern) {
        Calendar calendar = Calendar.getInstance();
        DateFormat dateFormat = new SimpleDateFormat(pattern);
        calendar.setTime(date);
        calendar.set(5, 1);
        calendar.roll(5, -1);
        return dateFormat.format(calendar.getTime());
    }

    public static Date addDays(Date date, int amount) {
        return add(date, 5, amount);
    }

    public static Date addWeeks(Date date, int amount) {
        return add(date, 3, amount);
    }

    public static Date addMonths(Date date, int amount) {
        return add(date, 2, amount);
    }

    public static Date addYears(Date date, int amount) {
        return add(date, 1, amount);
    }

    public static Date addHours(Date date, int amount) {
        return add(date, 11, amount);
    }

    public static Date addMinutes(Date date, int amount) {
        return add(date, 12, amount);
    }

    public static Date addSeconds(Date date, int amount) {
        return add(date, 13, amount);
    }

    public static Date addMilliseconds(Date date, int amount) {
        return add(date, 14, amount);
    }

    private static Date add(Date date, int calendarField, int amount) {
        if (date == null) {
            throw new IllegalArgumentException("The date must not be null");
        } else {
            Calendar c = Calendar.getInstance();
            c.setTime(date);
            c.add(calendarField, amount);
            return c.getTime();
        }
    }

    public static String formatDate(Date date, DateEnum fs) {
        DateEnum pattern = fs;
        if (date == null) {
            return "";
        } else {
            if (fs == null) {
                pattern = DateEnum.YYYYMMDD_BYSEP;
            }

            SimpleDateFormat sdf = new SimpleDateFormat(pattern.getValue());
            return sdf.format(date);
        }
    }

    public static String getNow(DateEnum fs) {
        return formatDate(now(), fs);
    }

    public static Date parseDate(String date, DateEnum fs) {
        if (date != null && date.length() != 0) {
            SimpleDateFormat formatter = new SimpleDateFormat(fs.getValue());

            try {
                return formatter.parse(date);
            } catch (ParseException var4) {
                var4.printStackTrace();
                return null;
            }
        } else {
            return null;
        }
    }

    public static String formatDate(Date date, String pattern) {
        String format = pattern;
        if (date == null) {
            return "";
        } else {
            if (pattern == null) {
                format = "yyyy-MM-dd";
            }

            SimpleDateFormat sdf = new SimpleDateFormat(format);
            return sdf.format(date);
        }
    }

    public static String formatDate(Date date, String pattern, TimeZone timeZone) {
        String format = pattern;
        if (date == null) {
            return "";
        } else {
            if (pattern == null) {
                format = "yyyy-MM-dd";
            }

            SimpleDateFormat sdf = new SimpleDateFormat(format);
            sdf.setTimeZone(timeZone);
            return sdf.format(date);
        }
    }

    public static String formatDateTime(Date date) {
        return formatDate(date, "yyyy-MM-dd HH:mm:ss");
    }

    public static String formatDateTime() {
        return formatDate(now(), "yyyyMMddHHmmssSSS");
    }

    public static String formatDateTime2() {
        return formatDate(now(), "yyyyMMddHHmmss");
    }

    public static String formatDateTimeMms(Date date) {
        return formatDate(date, "yyyy-MM-dd HH:mm:ss.SSS");
    }

    public static String formatDate(Date date) {
        return formatDate(date, "yyyy-MM-dd");
    }

    public static String formatDate2(Date date) {
        return formatDate(date, "yyyyMMdd");
    }

    public static String formatDate() {
        return formatDate(now(), "yyyy-MM-dd");
    }

    public static String formatDate2() {
        return formatDate(now(), "yyyyMMdd");
    }

    public static String formatTime(Date date) {
        return formatDate(date, "HH:mm:ss");
    }

    public static String formatTime() {
        return formatDate(now(), "HH:mm:ss");
    }

    public static String formatTime2() {
        return formatDate(now(), "HHmmss");
    }

    public static Date now() {
        return new Date();
    }

    public static Date parseDateTime(String datetime) {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        if (datetime != null && !"".equals(datetime)) {
            try {
                return formatter.parse(datetime);
            } catch (ParseException var3) {
                return parseDate(datetime);
            }
        } else {
            return null;
        }
    }

    public static Date parseDate(String date) {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        if (date != null && !"".equals(date)) {
            try {
                return formatter.parse(date);
            } catch (ParseException var3) {
                return null;
            }
        } else {
            return null;
        }
    }

    public static Date parseDate2(String date) {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd");
        if (date != null && !"".equals(date)) {
            try {
                return formatter.parse(date);
            } catch (ParseException var3) {
                return null;
            }
        } else {
            return null;
        }
    }

    public static Date parseDate(Date datetime) {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        if (datetime == null) {
            return null;
        } else {
            try {
                return formatter.parse(formatter.format(datetime));
            } catch (ParseException var3) {
                return null;
            }
        }
    }

    public static String formatDate(Object o) {
        if (o == null) {
            return "";
        } else if (o.getClass() == String.class) {
            return formatDate(o);
        } else if (o.getClass() == Date.class) {
            return formatDate(o);
        } else {
            return o.getClass() == Timestamp.class ? formatDate(new Date(((Timestamp)o).getTime())) : o.toString();
        }
    }

    public static String formatDateTime(Object o) {
        if (o.getClass() == String.class) {
            return formatDateTime(o);
        } else if (o.getClass() == Date.class) {
            return formatDateTime(o);
        } else {
            return o.getClass() == Timestamp.class ? formatDateTime(new Date(((Timestamp)o).getTime())) : o.toString();
        }
    }

    public static Date addMilliSecond(Date date, int amount) {
        return add(date, 14, amount);
    }

    public static Date addSecond(Date date, int amount) {
        return add(date, 13, amount);
    }

    public static Date addMiunte(Date date, int amount) {
        return add(date, 12, amount);
    }

    public static Date addHour(Date date, int amount) {
        return add(date, 10, amount);
    }

    public static Date addDay(Date date, int amount) {
        return add(date, 5, amount);
    }

    public static Date addMonth(Date date, int amount) {
        return add(date, 2, amount);
    }

    public static Date addYear(Date date, int amount) {
        return add(date, 1, amount);
    }

    public static Date getDate() {
        return parseDate(formatDate2());
    }

    public static Date getDateTime() {
        return parseDateTime(formatDateTime());
    }

    public static String parseDateString(String dateString) {
        return formatDate(parseDate2(dateString));
    }

    public static String formatTimeStamp(String dat, String tim, int len) {
        SimpleDateFormat df = new SimpleDateFormat(dat);
        return tim.length() > len ? df.format(Long.valueOf(tim)) : tim;
    }

    public static String formateDate(String dateTime) {
        return dateTime != null && !"".equals(dateTime) ? dateTime.substring(0, 4) + "年" + dateTime.substring(4, 6) + "月" + dateTime.substring(6, 8) + "日 " + dateTime.substring(8, 10) + ":" + dateTime.substring(10, 12) + ":" + dateTime.substring(12, 14) : "";
    }

    public static String secToTime(int time) {
        String timeStr = null;
        int hour = false;
        int minute = false;
        int second = false;
        if (time <= 0) {
            return "00:00";
        } else {
            int minute = time / 60;
            int second;
            if (minute < 60) {
                second = time % 60;
                timeStr = unitFormat(minute) + ":" + unitFormat(second);
            } else {
                int hour = minute / 60;
                minute %= 60;
                second = time - hour * 3600 - minute * 60;
                timeStr = unitFormat(hour) + ":" + unitFormat(minute) + ":" + unitFormat(second);
                timeStr = hour > 99 ? "99:59:59" : timeStr;
            }

            return timeStr;
        }
    }

    public static String unitFormat(int i) {
        String retStr = null;
        if (i >= 0 && i < 10) {
            retStr = "0" + Integer.toString(i);
        } else {
            retStr = "" + i;
        }

        return retStr;
    }

    public static String formatIOS8601(String dateStr) {
        return formatIOS8601(dateStr, false);
    }

    public static String formatIOS8601(String dateStr, boolean addOneDay) {
        if (StringUtils.isEmpty(dateStr)) {
            throw new RuntimeException("parse date error, date is empty");
        } else {
            Date date = null;
            if (StringUtils.length(dateStr) == 10) {
                date = parseISO8601(dateStr, "yyyy-MM-dd");
            } else if (StringUtils.length(dateStr) == 19) {
                date = parseISO8601(dateStr, "yyyy-MM-dd HH:mm:ss");
            }

            if (date == null) {
                throw new RuntimeException("parse date error, date length error. ");
            } else {
                Calendar instance = Calendar.getInstance();
                instance.setTime(date);
                instance.add(10, -8);
                if (addOneDay) {
                    instance.add(5, 1);
                }

                date = instance.getTime();
                return formatDate(date, "yyyy-MM-dd‘T‘HH:mm:ss‘Z‘");
            }
        }
    }

    public static Date parseISO8601(String dateStr, String pattern) {
        try {
            return parseDate(dateStr, pattern, TimeZone.getTimeZone("GMT+8"));
        } catch (ParseException var3) {
            return null;
        }
    }

    public static Integer compareTiems(Date time1, Date time2) {
        if (time1 != null && time2 != null) {
            Calendar c1 = Calendar.getInstance();
            Calendar c2 = Calendar.getInstance();
            c1.setTime(time1);
            c2.setTime(time2);
            return c1.compareTo(c2);
        } else {
            return null;
        }
    }

    public static int dateDiffByDay(Date begin, Date end) {
        return (int)((end.getTime() - begin.getTime()) / 24L / 3600000L);
    }

    public static int dateDiffBySec(Date begin, Date end) {
        return (int)((end.getTime() - begin.getTime()) / 1000L);
    }

    public static int dateDiffByMinute(Date begin, Date end) {
        return (int)((end.getTime() - begin.getTime()) / 1000L / 60L);
    }

    public static int dateDiffByHour(Date begin, Date end) {
        return (int)((end.getTime() - begin.getTime()) / 1000L / 3600L);
    }
}

 

Date工具类

标签:ast   amount   time   sunday   substring   substr   dmi   throws   else   

原文地址:https://www.cnblogs.com/hongqingfu/p/8251040.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!