日期工具类

  • Post author:
  • Post category:其他




日期工具类(1)

package com.hl.springbootmybatis.pojo;
 
import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateTime;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.apache.commons.lang3.StringUtils;
 
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 日期工具类
 */
public class DateTimeUtils {
    /** 日期格式 */
    public static final String DATE_FORMAT = "yyyy-MM-dd";
    /** 时间格式 */
    public static final String TIME_FORMAT = "yyyy-MM-dd HH:mm:ss";
    /** 默认时间 */
    public static final String TIME_FORMAT_SUFFIX = " 00:00:00";
    
    /**
     * 获得指定日期的days天偏移日期(yyyy-MM-dd)
     *
     * @param specifiedDay 指定日期, 为 null 时取当前日期
     * @param days 偏移量(天) 为负数时:指定日期的前days天;为正数时:指定日期的后days天; 为0时:取指定日期
     * @param isReturnString true 返回String类型 false 返回Date类型
     * @return 日期
     */
    public static DateResultModule getSpecifiedDate(String specifiedDay, int days, boolean isReturnString){
        if (StringUtils.isBlank(specifiedDay)) {
            specifiedDay = getCurrentOffsetDate(days);
        }
        Calendar c = Calendar.getInstance();
        Date date=null;
        try {
            date = new SimpleDateFormat(DATE_FORMAT).parse(specifiedDay);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        if (date != null) {
            c.setTime(date);
        }
        int day=c.get(Calendar.DATE);
        c.set(Calendar.DATE,day + days);
        DateResultModule dateResultModule = new DateResultModule();
        if (isReturnString) {
            dateResultModule.setIsString(new SimpleDateFormat(DATE_FORMAT).format(c.getTime()));
        } else {
            dateResultModule.setIsDate(c.getTime());
        }
        return dateResultModule;
    }
 
    /**
     * 获得指定日期的days天偏移时间(yyyy-MM-dd HH:mm:ss)
     *
     * @param specifiedDay 指定时间, 为 null 时取当前时间
     * @param days 偏移量(天) 为负数时:取指定时间的前days天;为正数时:取指定时间的后days天;为0时:取指定时间
     * @param isReturnString true 返回String类型 false 返回Date类型
     * @return 时间
     */
    public static DateResultModule getSpecifiedTime(String specifiedDay, int days, boolean isReturnString){
        if (StringUtils.isBlank(specifiedDay)) {
            specifiedDay = getCurrentOffsetDateToSecond(days);
        }
        if (specifiedDay.length() < 11) { // 指定时间为日期格式时转为默认的时间格式
            specifiedDay += TIME_FORMAT_SUFFIX;
        }
        Calendar c = Calendar.getInstance();
        Date date=null;
        try {
            date = new SimpleDateFormat(TIME_FORMAT).parse(specifiedDay);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        if (date != null) {
            c.setTime(date);
        }
        int day=c.get(Calendar.DATE);
        c.set(Calendar.DATE,day + days);
        DateResultModule dateResultModule = new DateResultModule();
        if (isReturnString) {
            dateResultModule.setIsString(new SimpleDateFormat(TIME_FORMAT).format(c.getTime()));
        } else {
            dateResultModule.setIsDate(c.getTime());
        }
        return dateResultModule;
    }

    /**
     * 返回当前日期 偏移日期 日期格式 yyyy-MM-dd
     * days 为负数 是当前前几天 为正数是当前后几天
     * @return 字符串日期
     */
    public static String getCurrentOffsetDate(int days) {
        return (new DateTime()).offsetNew(DateField.HOUR, 24 * days).toString(DATE_FORMAT);
    }
 
    /**
     * 返回当前日期 偏移日期 日期格式 yyyy-MM-dd  HH:mm:ss
     * days 为负数 是当前前几天 为正数是当前后几天
     * @return
     */
    public static String getCurrentOffsetDateToSecond(int days) {
        return (new DateTime()).offsetNew(DateField.HOUR, 24 * days).toString(TIME_FORMAT);
    }

    /**
     * 获取当月开始时间戳
     *
     * @param timeStamp 毫秒级时间戳
     * @return 时间戳
     */
    public static Long getMonthStartTime(Long timeStamp) {
        Calendar calendar = Calendar.getInstance();// 获取当前日期
        calendar.setTimeZone(TimeZone.getTimeZone("GMT+8:00"));
        calendar.setTimeInMillis(timeStamp);
        calendar.add(Calendar.YEAR, 0);
        calendar.add(Calendar.MONTH, 0);
        calendar.set(Calendar.DAY_OF_MONTH, 1);// 设置为1号,当前日期既为本月第一天
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.MILLISECOND, 0);
        return calendar.getTimeInMillis();
    }

    /**
     * 时间戳转换成日期格式字符串
     *
     * @param seconds 精确到秒的字符串
     * @param format
     * @return
     */
    public static String timeStamp2DateStr(String seconds, String format) {
        if (seconds == null || seconds.isEmpty() || seconds.equals("null")) {
            return "";
        }
        if (format == null || format.isEmpty()) {
            format = "yyyy-MM-dd HH:mm:ss";
        }
        TimeZone timeZone = TimeZone.getTimeZone("GMT+8:00");
        SimpleDateFormat sdf = new SimpleDateFormat(format);
        sdf.setTimeZone(timeZone);
        return sdf.format(new Date(Long.parseLong(seconds + "000")));
    }

    /**
     * 时间戳转换成日期格式字符串
     *
     * @param timestamp 精确到毫秒
     * @param format
     * @return
     */
    public static String timeStamp2DateStr2(long timestamp, String format) {
        TimeZone timeZone = TimeZone.getTimeZone("GMT+8:00");
        if (format == null || format.isEmpty()) {
            format = "yyyy-MM-dd HH:mm:ss";
        }
        SimpleDateFormat sdf = new SimpleDateFormat(format);
        sdf.setTimeZone(timeZone);
        return sdf.format(new Date(timestamp));
    }

    /**
     * 日期格式字符串转换成时间戳
     *
     * @param date_str 字符串日期
     * @param format   如:yyyy-MM-dd HH:mm:ss
     * @return
     */
    public static String dateStr2TimeStamp(String date_str, String format) {
        try {
            TimeZone timeZone = TimeZone.getTimeZone("GMT+8:00");
            SimpleDateFormat sdf = new SimpleDateFormat(format);
            sdf.setTimeZone(timeZone);
            return String.valueOf(sdf.parse(date_str).getTime());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    /**
     * 日期格式字符串转换成时间戳
     *
     * @param date_str 字符串日期
     * @param format   如:yyyy-MM-dd HH:mm:ss
     * @return
     */
    public static long dateStr2TimeStampLong(String date_str, String format) {
        try {
            TimeZone timeZone = TimeZone.getTimeZone("GMT+8:00");
            SimpleDateFormat sdf = new SimpleDateFormat(format);
            sdf.setTimeZone(timeZone);
            return sdf.parse(date_str).getTime();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return 0L;
    }

    /**
     *  java 获取 获取某年某月 所有日期(yyyy-mm-dd格式字符串)
     * @param year
     * @param month
     * @return
     */
    public static List<String> getMonthFullDay(int year, int month){
        SimpleDateFormat dateFormatYYYYMMDD = new SimpleDateFormat("yyyy-MM-dd");
        List<String> fullDayList = new ArrayList<>(32);
        // 获得当前日期对象
        Calendar cal = Calendar.getInstance();
        cal.clear();// 清除信息
        cal.set(Calendar.YEAR, year);
        // 1月从0开始
        cal.set(Calendar.MONTH, month-1 );
        // 当月1号
        cal.set(Calendar.DAY_OF_MONTH,1);
        int count = cal.getActualMaximum(Calendar.DAY_OF_MONTH);
        for (int j = 1; j <= count ; j++) {
            fullDayList.add(dateFormatYYYYMMDD.format(cal.getTime()));
            cal.add(Calendar.DAY_OF_MONTH,1);
        }
        return fullDayList;
    }

    /**
     * 获取上个月开始时间戳
     *
     * @param timeStamp 毫秒级时间戳
     * @return 时间戳
     */
    public static Long getLastMonthStartTime(Long timeStamp){
        Calendar calendar = Calendar.getInstance();// 获取当前日期
        calendar.setTimeZone(TimeZone.getTimeZone("GMT+8:00"));
        calendar.setTimeInMillis(timeStamp);
        calendar.add(Calendar.YEAR, 0);
        calendar.add(Calendar.MONTH,-1);
        calendar.set(Calendar.DAY_OF_MONTH,1);
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.MILLISECOND, 0);
        return calendar.getTimeInMillis();
    }

    /**
     * 获取当前月的第一天
     * @param timeStamp 时间戳
     * @return 毫秒值
     */
    public static Long getNowMonthStartTime(Long timeStamp){
        Calendar calendar = Calendar.getInstance();// 获取当前日期
        calendar.setTimeZone(TimeZone.getTimeZone("GMT+8:00"));
        calendar.setTimeInMillis(timeStamp);
        calendar.set(Calendar.DAY_OF_MONTH,1);
        calendar.set(Calendar.HOUR_OF_DAY,0);
        calendar.set(Calendar.MINUTE,0);
        calendar.set(Calendar.SECOND,0);
        calendar.set(Calendar.MILLISECOND,0);
        return calendar.getTimeInMillis();
    }
    /**
     * 获取当月的结束时间戳
     *
     * @param timeStamp 毫秒级时间戳
     * @return 时间戳
     */
    public static Long getMonthEndTime(Long timeStamp) {
        Calendar calendar = Calendar.getInstance();// 获取当前日期
        calendar.setTimeZone(TimeZone.getTimeZone("GMT+8:00"));
        calendar.setTimeInMillis(timeStamp);
        calendar.add(Calendar.YEAR, 0);
        calendar.add(Calendar.MONTH, 0);
        calendar.set(Calendar.DAY_OF_MONTH, calendar.getActualMaximum(Calendar.DAY_OF_MONTH));// 获取当前月最后一天
        calendar.set(Calendar.HOUR_OF_DAY, 23);
        calendar.set(Calendar.MINUTE, 59);
        calendar.set(Calendar.SECOND, 59);
        calendar.set(Calendar.MILLISECOND, 999);
        return calendar.getTimeInMillis();
    }

    /**
     * 获取两个时间节点之间的星期列表
     **/
    public static Set<Integer> getWeekBetween(long t1, long t2) {
        Set<Integer> result = new HashSet<>();
        Calendar min = Calendar.getInstance();
        Calendar max = Calendar.getInstance();
        TimeZone timeZone = TimeZone.getTimeZone("GMT+8:00");
        min.setTimeZone(timeZone);
        max.setTimeZone(timeZone);
        min.setTimeInMillis(t1);
        max.setTimeInMillis(t2);
        result.add(min.get(Calendar.DAY_OF_WEEK));
        result.add(max.get(Calendar.DAY_OF_WEEK));
        while (min.before(max)) {
            result.add(min.get(Calendar.DAY_OF_WEEK));
            min.add(Calendar.DAY_OF_WEEK, 1);
        }
        return result;
    }

    /**
     * 获取过去一年时间的月份列表
     **/
    public static List<String> getYearMonthBetween(long t1) {
        List<String> result = new ArrayList<>();
        //格式化为年月
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
        Calendar max = Calendar.getInstance();
        TimeZone timeZone = TimeZone.getTimeZone("GMT+8:00");
        max.setTimeZone(timeZone);
        max.setTimeInMillis(t1);
        Calendar min = Calendar.getInstance();
        min.setTimeInMillis(t1);
        min.setTimeZone(timeZone);
        min.add(Calendar.YEAR, -1);
        while (min.before(max)) {
            min.add(Calendar.MONTH, 1);
            result.add(sdf.format(min.getTime()));
        }
        return result;
    }

    /**
     * 获取两个时间节点之间的月份列表
     **/
    public static Set<Integer> getMonthBetween(long t1, long t2) {
        Set<Integer> result = new HashSet<>();
        Calendar min = Calendar.getInstance();
        Calendar max = Calendar.getInstance();
        TimeZone timeZone = TimeZone.getTimeZone("GMT+8:00");
        min.setTimeZone(timeZone);
        max.setTimeZone(timeZone);
        min.setTimeInMillis(t1);
        max.setTimeInMillis(t2);
        result.add(min.get(Calendar.MONTH));
        result.add(max.get(Calendar.MONTH));
        while (min.before(max)) {
            result.add(min.get(Calendar.MONTH));
            min.add(Calendar.MONTH, 1);
        }
        return result;
    }



    /**
     * 取得当前时间戳(精确到秒)
     *
     * @return
     */
    public static String timeStamp() {
        long time = System.currentTimeMillis();
        return String.valueOf(time / 1000);
    }

    /**
     * 根据当前时间获取这个月的天数
     * @param time 当前时间
     * @return 天数
     */
    public static int getDayOfMonth(Long time){
        Calendar calendar = Calendar.getInstance();
        calendar.setTimeZone(TimeZone.getTimeZone("GMT+8:00"));
        calendar.setTimeInMillis(time);
        return calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
    }


    /**
     * 根据指定年月获取这个月的开始时间
     * @param year
     * @param month
     * @return
     */
    public static long getMothBegin(int year, int month) {
        Calendar calendar = Calendar.getInstance();
        TimeZone timeZone = TimeZone.getTimeZone("GMT+8:00");
        calendar.setTimeZone(timeZone);
        calendar.set(Calendar.YEAR, year);
        // 1月从0开始
        calendar.set(Calendar.MONTH, month-1 );
        // 当月1号
        calendar.set(Calendar.DAY_OF_MONTH, 1);// 设置为1号,当前日期既为本月第一天
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        return calendar.getTimeInMillis();

    }


    /**
     * 获取指定日期所在月份开始的时间戳
     * @param year
     * @param month
     * @return
     */
    public static Long getMonthEnd(int year, int month) {
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.YEAR, year);
        // 1月从0开始
        calendar.set(Calendar.MONTH, month-1 );
        calendar.set(Calendar.DAY_OF_MONTH, calendar.getActualMaximum(Calendar.DAY_OF_MONTH));
        //将小时至23
        calendar.set(Calendar.HOUR_OF_DAY, 23);
        //将分钟至59
        calendar.set(Calendar.MINUTE, 59);
        //将秒至59
        calendar.set(Calendar.SECOND,59);
        //将毫秒至999
        calendar.set(Calendar.MILLISECOND, 999);

        // 获取本月第一天的时间戳
        return calendar.getTimeInMillis();
    }
    @Data
    @Builder
    @AllArgsConstructor
    @NoArgsConstructor
    public static class DateResultModule {
        private Date isDate;
        private String isString;
    }
}


 @Test
    public void testSelectAll() throws JsonProcessingException {
        String todayStr = DateTimeUtils.getSpecifiedTime(null, 0, true).getIsString();
        // 当前日期
        Date todayDate = DateTimeUtils.getSpecifiedDate(null, 0, false).getIsDate();

        // 七天前的时间(七天后:  days 参数为 7 )
        String sevenDaysBeforeStr = DateTimeUtils.getSpecifiedTime(null, -7, true).getIsString();
        // 七天前的日期(七天后:  days 参数为 7 )
        Date sevenDaysAfterDate = DateTimeUtils.getSpecifiedDate(null, -7, false).getIsDate();

        // 2021年1月1日的三天前的时间
        String specifiedTime = DateTimeUtils.getSpecifiedTime("2021-01-01 11:11:11", -3, true).getIsString();
        // 2021年1月1日的三天前的日期
        Date specifiedDate = DateTimeUtils.getSpecifiedDate("2021-01-01", -3, false).getIsDate();

        System.out.println(todayStr);
        System.out.println(todayDate);
        System.out.println(sevenDaysBeforeStr);
        System.out.println(sevenDaysAfterDate);
        System.out.println(specifiedTime);
        System.out.println(specifiedDate);
    }

在这里插入图片描述



日期工具类(2)

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

/**
 * 日期工具类
 */
public class DateUtils {
    public static final String DAFAULT_DATE_FORMAT = "yyyy-M-d";
    public static final String DATE_FORMAT = "yyyy-MM-dd";
    public static final String DAFAULT_DATETIME_FORMAT = "yyyy-M-d HH:mm:ss";
    public static final String DATETIME_FORMAT = "yyyy-MM-dd HH:mm:ss";
    public static final String DAFAULT_TIME_FORMAT = "HH:mm:ss";

    /**
     * 默认构造方法
     */
    private DateUtils() {

    }

    /**
     * 当前时间
     *
     * @return date
     */
    public static Date currentDate() {
        return Calendar.getInstance().getTime();
    }

    /**
     * 得到年
     *
     * @param c
     * @return
     */
    public static int getYear(Calendar c) {
        if (c != null) {
            return c.get(Calendar.YEAR);
        } else {
            return Calendar.getInstance().get(Calendar.YEAR);
        }
    }

    /**
     * 得到月份
     * 注意,这里的月份依然是从0开始的
     *
     * @param c
     * @return
     */
    public static int getMonth(Calendar c) {
        if (c != null) {
            return c.get(Calendar.MONTH) + 1;
        } else {
            return Calendar.getInstance().get(Calendar.MONTH) + 1;
        }
    }

    /**
     * 得到日期
     *
     * @param c
     * @return
     */
    public static int getDate(Calendar c) {
        if (c != null) {
            return c.get(Calendar.DATE);
        } else {
            return Calendar.getInstance().get(Calendar.DATE);
        }
    }

    /**
     * 得到星期
     *
     * @param c
     * @return
     */
    public static int getDay(Calendar c) {
        if (c != null) {
            return c.get(Calendar.DAY_OF_WEEK);
        } else {
            return Calendar.getInstance().get(Calendar.DAY_OF_WEEK);
        }
    }

    /**
     * 得到小时
     *
     * @param c
     * @return
     */
    public static int getHour(Calendar c) {
        if (c != null) {
            return c.get(Calendar.HOUR_OF_DAY);
        } else {
            return Calendar.getInstance().get(Calendar.HOUR_OF_DAY);
        }
    }

    /**
     * 得到分钟
     *
     * @param c
     * @return
     */
    public static int getMinute(Calendar c) {
        if (c != null) {
            return c.get(Calendar.MINUTE);
        } else {
            return Calendar.getInstance().get(Calendar.MINUTE);
        }
    }

    /**
     * 得到秒
     *
     * @param c
     * @return
     */
    public static int getSecond(Calendar c) {
        if (c != null) {
            return c.get(Calendar.SECOND);
        } else {
            return Calendar.getInstance().get(Calendar.SECOND);
        }
    }

    /**
     * 得到指定或者当前时间前n天的Calendar
     *
     * @param c
     * @param n
     * @return
     */
    public static Calendar beforeNDays(Calendar c, int n) {
        //偏移量,给定n天的毫秒数
        long offset = n * 24 * 60 * 60 * 1000;
        Calendar calendar = null;
        if (c != null) {
            calendar = c;
        } else {
            calendar = Calendar.getInstance();
        }

        calendar.setTimeInMillis(calendar.getTimeInMillis() - offset);
        return calendar;
    }

    /**
     * 得到指定或者当前时间后n天的Calendar
     *
     * @param c
     * @param n
     * @return
     */
    public static Calendar afterNDays(Calendar c, int n) {
        //偏移量,给定n天的毫秒数
        long offset = n * 24 * 60 * 60 * 1000;
        Calendar calendar = null;
        if (c != null) {
            calendar = c;
        } else {
            calendar = Calendar.getInstance();
        }

        calendar.setTimeInMillis(calendar.getTimeInMillis() + offset);
        return calendar;
    }

    /**
     * 指定日期加月份
     *
     * @param date      指定日期
     * @param addMonths 要加的月份数
     * @return Date 计算后的日期
     */
    public static Date addMonths(Date date, int addMonths) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.add(Calendar.MONTH, addMonths);
        return calendar.getTime();
    }

    /**
     * 当前日期加月份
     *
     * @param addMonths 要加的月份数
     * @return Date 计算后的日期
     */
    public static Date addMonths(int addMonths) {
        return addMonths(new Date(), addMonths);
    }

    /**
     * 指定日期加天
     *
     * @param date    指定日期
     * @param addDays 要加的天数
     * @return Date 计算后的日期
     */
    public static Date addDays(Date date, int addDays) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.add(Calendar.DATE, addDays);
        return calendar.getTime();
    }

    /**
     * 当前日期加天
     *
     * @param addDays 要加的天数
     * @return Date 计算后的日期
     */
    public static Date addDays(int addDays) {
        return addDays(new Date(), addDays);
    }

    /**
     * 指定日期加小时
     *
     * @param date     指定日期
     * @param addHours 要加的小时数
     * @return Date 计算后的日期
     */
    public static Date addHours(Date date, int addHours) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.add(Calendar.HOUR, addHours);
        return calendar.getTime();
    }

    /**
     * 当前日期加小时
     *
     * @param addHours 要加的小时数
     * @return Date 计算后的日期
     */
    public static Date addHours(int addHours) {
        return addHours(new Date(), addHours);
    }

    /**
     * 指定日期加分
     *
     * @param date       指定日期
     * @param addMinutes 要加的分数
     * @return Date 计算后的日期
     */
    public static Date addMinutes(Date date, int addMinutes) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.add(Calendar.MINUTE, addMinutes);
        return calendar.getTime();
    }

    /**
     * 当前日期加分
     *
     * @param addMinutes 要加的分数
     * @return Date 计算后的日期
     */
    public static Date addMinutes(int addMinutes) {
        return addMinutes(new Date(), addMinutes);
    }

    /**
     * 指定日期加秒
     *
     * @param date       指定日期
     * @param addSeconds 要加的秒数
     * @return Date 计算后的日期
     */
    public static Date addSeconds(Date date, int addSeconds) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.add(Calendar.SECOND, addSeconds);
        return calendar.getTime();
    }

    /**
     * 当前日期加秒
     *
     * @param addSeconds 要加的秒数
     * @return Date 计算后的日期
     */
    public static Date addSeconds(int addSeconds) {
        return addSeconds(new Date(), addSeconds);
    }

    /**
     * 昨天
     *
     * @param c
     * @return
     */
    public static Calendar yesterday(Calendar c) {
        long offset = 1 * 24 * 60 * 60 * 1000;
        Calendar calendar = null;
        if (c != null) {
            calendar = c;
        } else {
            calendar = Calendar.getInstance();
        }
        calendar.setTimeInMillis(calendar.getTimeInMillis() - offset);
        return calendar;
    }

    /**
     * 明天
     *
     * @param c
     * @return
     */
    public static Calendar tomorrow(Calendar c) {
        long offset = 1 * 24 * 60 * 60 * 1000;
        Calendar calendar = null;
        if (c != null) {
            calendar = c;
        } else {
            calendar = Calendar.getInstance();
        }

        calendar.setTimeInMillis(calendar.getTimeInMillis() + offset);
        return calendar;
    }

    /**
     * 得到指定或者当前时间前offset毫秒的Calendar
     *
     * @param c
     * @param offset
     * @return
     */
    public static Calendar before(Calendar c, long offset) {
        Calendar calendar = null;
        if (c != null) {
            calendar = c;
        } else {
            calendar = Calendar.getInstance();
        }

        calendar.setTimeInMillis(calendar.getTimeInMillis() - offset);
        return calendar;
    }

    /**
     * 得到指定或者当前时间前offset毫秒的Calendar
     *
     * @param c
     * @param offset
     * @return
     */
    public static Calendar after(Calendar c, long offset) {
        Calendar calendar = null;
        if (c != null) {
            calendar = c;
        } else {
            calendar = Calendar.getInstance();
        }

        calendar.setTimeInMillis(calendar.getTimeInMillis() - offset);
        return calendar;
    }

    /**
     * 日期格式化
     *
     * @param c
     * @param pattern
     * @return
     */
    public static String format(Calendar c, String pattern) {
        Calendar calendar = null;
        if (c != null) {
            calendar = c;
        } else {
            calendar = Calendar.getInstance();
        }
        if (pattern == null || pattern.equals("")) {
            pattern = DATETIME_FORMAT;
        }
        SimpleDateFormat sdf = new SimpleDateFormat(pattern);

        return sdf.format(calendar.getTime());
    }

    /**
     * 日期格式化
     *
     * @param date    日期
     * @param pattern 格式
     * @return String 格式化字符串
     */
    public static String format(Date date, String pattern) {
        Date tempDate = null;
        if (date != null) {
            tempDate = date;
        } else {
            tempDate = Calendar.getInstance().getTime();
        }
        if (pattern == null || pattern.equals("")) {
            pattern = DATETIME_FORMAT;
        }
        SimpleDateFormat sdf = new SimpleDateFormat(pattern);

        return sdf.format(tempDate);
    }

    /**
     * Date类型转换到Calendar类型
     *
     * @param d
     * @return
     */
    public static Calendar date2Calendar(Date d) {
        Calendar c = Calendar.getInstance();
        c.setTime(d);
        return c;
    }

    /**
     * Calendar类型转换到Date类型
     *
     * @param c
     * @return
     */
    public static Date calendar2Date(Calendar c) {
        return c.getTime();
    }

    /**
     * Date类型转换到Timestamp类型
     *
     * @param d
     * @return
     */
    public static Timestamp date2Timestamp(Date d) {
        return new Timestamp(d.getTime());
    }

    /**
     * Calendar类型转换到Timestamp类型
     *
     * @param c
     * @return
     */
    public static Timestamp calendar2Timestamp(Calendar c) {
        return new Timestamp(c.getTimeInMillis());
    }

    /**
     * Timestamp类型转换到Calendar类型
     *
     * @param ts
     * @return
     */
    public static Calendar timestamp2Calendar(Timestamp ts) {
        Calendar c = Calendar.getInstance();
        c.setTime(ts);
        return c;
    }

    /**
     * 得到当前时间的字符串表示
     * 格式2010-02-02 12:12:12
     *
     * @return
     */
    public static String getTimeString() {
        return format(Calendar.getInstance(), DATETIME_FORMAT);
    }

    /**
     * 标准日期格式字符串解析成Calendar对象
     *
     * @param s
     * @return
     */
    public static Calendar pars2Calender(String s) {
        Timestamp ts = Timestamp.valueOf(s);
        return timestamp2Calendar(ts);
    }

}



版权声明:本文为weixin_43296313原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。