Java时间处理工具类

package com;


import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.TimeZone;

/**
 * 时间工具类
 */
public class DateUtil {

   private static Log logger = LogFactory.getLog(DateUtil.class);

   /**
    * 日期格式:MM-dd
    */
   public static final String FORMAT_DATE_MMDD_WITH_HYPHEN = "MM-dd";

   /**
    * 日期格式:yyyyMMdd
    */
   public static final String FORMAT_DATE_YYYYMMDD = "yyyyMMdd";

   /**
    * 日期格式:yyyy-MM-dd
    */
   public static final String FORMAT_DATE_YYYYMMDD_WITH_HYPHEN = "yyyy-MM-dd";

   /**
    * 日期格式:yyyy/MM/dd
    */
   public static final String FORMAT_DATE_YYYYMMDD_WITH_SLASH = "yyyy/MM/dd";

   /**
    * 日期格式:yyyy/MM/dd HH:mm:ss
    */
   public static final String FORMAT_DATETIME_WITH_SLASH = "yyyy/MM/dd HH:mm:ss";

   /**
    * 日期格式:yyyy/MM/dd HH:mm:ss
    */
   public static final String FORMAT_DATETIME_WITH_SLASH_ = "yyyy-MM-dd HH:mm:ss";

   /**
    * 获得当前系统日期
    * @param format 日期格式
    * @return Date
    * @author mshi
    */
   public static final String getCurrentDateStr(String format){
      return format(getCurrentDate(), format);
   }

   /**
    * 获得当前系统时间
    * 格式yyyy-MM-dd HH:mm:ss
    * @return Date
    * @author mshi
    */
   public static final Date getCurrentTime(){
      return Calendar.getInstance().getTime();
   }
   
   /**
    * 获得当前系统时间
    * 格式 yyyy-MM-dd
    * @return Date
    * @author mshi
    */
   public static final Date getCurrentDate(){
      return getDateIgnoreTime(Calendar.getInstance().getTime());
   }
   
   /**
    * 获取时间上下间隔
    * @param baseDate
    * @return Date[]
    * @author mshi
    */
   public static final Date[] getDifferenceDate(Date baseDate) {
      Date[] date = new Date[2];
      Calendar cal = Calendar.getInstance();
      cal.setTime(baseDate);
      cal.set(Calendar.HOUR_OF_DAY, 0);
      cal.set(Calendar.MINUTE, 0);
      cal.set(Calendar.SECOND, 0);
      cal.set(Calendar.MILLISECOND, 0);
      date[0] = cal.getTime();
      cal.add(Calendar.DATE, 1);
      date[1] = cal.getTime();
      return date;
   }

   /**
    * 将时间的时分秒毫秒归零
    * @param baseDate
    * @return Date
    * @author mshi
    */
   public static final Date getDateIgnoreTime(Date baseDate) {
      Calendar cal = Calendar.getInstance();
      cal.setTime(baseDate);
      cal.set(Calendar.HOUR_OF_DAY, 0);
      cal.set(Calendar.MINUTE, 0);
      cal.set(Calendar.SECOND, 0);
      cal.set(Calendar.MILLISECOND, 0);
      return cal.getTime();
   }

   /**
    * 将时间的分秒毫秒归零
    * @param baseDate
    * @return Date
    * @author mshi
    */
   public static final Date getDateIgnoreHour(Date baseDate) {
      Calendar cal = Calendar.getInstance();
      cal.setTime(baseDate);
      cal.set(Calendar.MINUTE, 0);
      cal.set(Calendar.SECOND, 0);
      cal.set(Calendar.MILLISECOND, 0);
      return cal.getTime();
   }

   /**
    * 比较两个日期差,精确到天
    * @param date1
    * @param date2
    * @return int
    * @author mshi
    */
   public static final int compareByDate(Date date1, Date date2) {
      int num = getDaysBetweenDates(date1, date2);
      if (num > 0)
         return 1;
      else if (num < 0)
         return -1;
      return num;
    }
    
   /**
    * 获得两个日期差几天,精确到秒
    * @param date1
    * @param date2
    * @return int
    * @author mshi
    */
   public static final int compareByDateTime(Date date1, Date date2) {
      if (date1 == null || date2 == null) {
         throw new IllegalArgumentException("Date cannot be null.");
      }
      TimeZone timeZone = TimeZone.getDefault();
      long beginOffset = timeZone.getRawOffset();
      long endOffset = beginOffset;
      if (timeZone.inDaylightTime(date1)) beginOffset += timeZone.getDSTSavings();
      if (timeZone.inDaylightTime(date2)) endOffset += timeZone.getDSTSavings();
      long milli1 = (date1.getTime() + beginOffset) / 1000;
      long milli2 = (date2.getTime() + endOffset) / 1000;
      int retVal = 0;
      if (milli1 > milli2) {
         retVal = 1;
      } else if (milli1 < milli2) {
         retVal = -1;
      }
      return retVal;
   }
   
   /**
    * 获得两个日期差几天,精确到毫秒
    * @param date1
    * @param date2
    * @return int
    * @author mshi
    */    
   public static final int compareByTimestamp(Date date1, Date date2) {
      if(date1 ==null || date2 == null) {
         throw new IllegalArgumentException("Date cannot be null.");  
      }     
      TimeZone timeZone = TimeZone.getDefault();
        long beginOffset = timeZone.getRawOffset();
      long endOffset = beginOffset;
      if (timeZone.inDaylightTime(date1)) beginOffset += timeZone.getDSTSavings();
      if (timeZone.inDaylightTime(date2)) endOffset += timeZone.getDSTSavings();
      long milli1=date1.getTime() + beginOffset;
      long milli2=date2.getTime() + endOffset;
      int retVal = 0;
      if (milli1 > milli2) {
         retVal = 1;
      } else if (milli1 < milli2) {
         retVal = -1;
      }
      return retVal;
   }
   
    /**
     * 获得两个日期差几天
     * @param endDate
     * @param beginDate
     * @return int
    * @author mshi
     */
   public static final int getDaysBetweenDates(Date endDate, Date beginDate) {
      if (endDate == null || beginDate == null) {
         throw new IllegalArgumentException("Date cannot be null.");  
      }
      return(getDaysBetweenDates((TimeZone)null, endDate, beginDate));
   }
   
   /**
    * 获得两个日期差几天
    * @param timeZone
    * @param endDate
    * @param beginDate
    * @return int
    * @author mshi
    */
   public static final int getDaysBetweenDates(TimeZone timeZone, Date endDate, Date beginDate) {
      if (beginDate == null || endDate == null)
         throw new IllegalArgumentException("Date cannot be null.");
      if (timeZone == null) timeZone = TimeZone.getDefault();
      long beginOffset = timeZone.getRawOffset();
      long endOffset = beginOffset;
      if (timeZone.inDaylightTime(beginDate)) beginOffset += timeZone.getDSTSavings();
      if (timeZone.inDaylightTime(endDate)) endOffset += timeZone.getDSTSavings();
      long endDays = (long)((endDate.getTime() + endOffset) / 86400000L);
      long beginDays = (long)((beginDate.getTime() + beginOffset) / 86400000L);
      return((int)(endDays - beginDays));
   }
   
   /**
    * 获得年份
    * @param date
    * @return int
    * @author mshi
    */
   public static final int getYear(Date date) {
        if (date == null) return 0;
        return getCalendarField(date, Calendar.YEAR);
    }
   
   /**
    * 获得月份
    * @param date
    * @return int
    * @author mshi
    */
    public static final int getMonth(Date date) {
        if (date == null) return 0;
        return getCalendarField(date, Calendar.MONTH) + 1;
    }
    
    /**
     * 获得天数
     * @param date
     * @return int
    * @author mshi
     */
    public static final int getDay(Date date) {
        if (date == null) return 0;
        return getCalendarField(date, Calendar.DAY_OF_MONTH);
    }
    
    /**
     * 获得小时
     * @param date
     * @return int
    * @author mshi
     */
    public static final int getHour(Date date) {
        if (date == null) return 0;
        return getCalendarField(date, Calendar.HOUR_OF_DAY);
    }
    
    /**
     * 获得分钟
     * @param date
     * @return int
    * @author mshi
     */
    public static final int getMinute(Date date) {
        if (date == null) return 0;
        return getCalendarField(date, Calendar.HOUR_OF_DAY);
    }
    
    /**
     * 获得秒
     * @param date
     * @return int
    * @author mshi
     */  
    public static final int getSecond(Date date) {
        if (date == null) return 0;
        return getCalendarField(date, Calendar.SECOND);
    }
    
    /**
     * 获得毫秒
     * @param date
     * @return int
    * @author mshi
     */
    public static final int getMilliSecond(Date date) {
        if (date == null) return 0;
        return getCalendarField(date, Calendar.MILLISECOND);
    }  
    
    /**
     * 返回给定日历字段的值
     * @param date
     * @param field
     * @return int
    * @author mshi
     */
    public static final int getCalendarField(Date date, int field){
      Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        return cal.get(field);
   }
    
    /**
     * 添加或减去指定的时间量,按年
     * @param date
     * @param value
     * @return Date
    * @author mshi
     */
    public static final Date addYear(Date date, int value){
       return add(date, Calendar.YEAR, value);
    } 

    /**
     * 添加或减去指定的时间量,按月
     * @param date
     * @param value
     * @return Date
    * @author mshi
     */
    public static final Date addMonth(Date date, int value){
       return add(date, Calendar.MONTH, value);
    } 
    
    /**
     * 添加或减去指定的时间量,按日
     * @param date
     * @param value
     * @return Date
    * @author mshi
     */
    public static final Date addDay(Date date, int value){
       return add(date, Calendar.DAY_OF_MONTH, value);
    }
    
    /**
     * 添加或减去指定的时间量,按小时
     * @param date
     * @param value
     * @return Date
    * @author mshi
     */
    public static final Date addHour(Date date, int value) {
        return add(date, Calendar.HOUR_OF_DAY, value);
    }
    
    /**
     * 添加或减去指定的时间量,按分钟
     * @param date
     * @param value
     * @return Date
    * @author mshi
     */
    public static final Date addMinute(Date date, int value) {
       return add(date, Calendar.MINUTE, value);
    }
    
    /**
     * 添加或减去指定的时间量,按秒
     * @param date
     * @param value
     * @return Date
    * @author mshi
     */
    public static final Date addSecond(Date date, int value) {
       return add(date, Calendar.SECOND, value);
    }
    
    /**
     * 添加或减去指定的时间量,按毫秒
     * @param date
     * @param value
     * @return Date
    * @author mshi
     */
    public static final Date addMilliSecond(Date date, int value) {
       return add(date, Calendar.MILLISECOND, value);
    }  
    
    /**
     * 添加或减去指定的时间量
     * @param date
     * @param field
     * @param value
     * @return Date
    * @author mshi
     */
    public static final Date add(Date date, int field, int value){
       Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        cal.add(field, value);
        return cal.getTime();
    }
    
    /**
     * 设置指定的时间量,按年
     * @param date
     * @param value
     * @return Date
    * @author mshi
     */
    public static final Date setYear(Date date, int value){
       return set(date, Calendar.YEAR, value);
    } 
    
    /**
     * 设置指定的时间量,按月
     * @param date
     * @param value
     * @return Date
    * @author mshi
     */
    public static final Date setMonth(Date date, int value){
       return set(date, Calendar.MONTH, value);
    } 
    
    /**
     * 设置指定的时间量,按日
     * @param date
     * @param value
     * @return Date
    * @author mshi
     */    
    public static final Date setDay(Date date, int value){
       return set(date, Calendar.DAY_OF_MONTH, value);
    }
    
    /**
     * 设置指定的时间量,按小时
     * @param date
     * @param value
     * @return Date
    * @author mshi
     */
    public static final Date setHour(Date date, int value) {
        return set(date, Calendar.HOUR_OF_DAY, value);
    }
    
    /**
     * 设置指定的时间量,按分钟
     * @param date
     * @param value
     * @return Date
    * @author mshi
     */
    public static final Date setMinute(Date date, int value) {
       return set(date, Calendar.HOUR_OF_DAY, value);
    }
    
    /**
     * 设置指定的时间量,按秒
     * @param date
     * @param value
     * @return Date
    * @author mshi
     */
    public static final Date setSecond(Date date, int value) {
       return set(date, Calendar.SECOND, value);
    }
    
    /**
     * 设置指定的时间量,按毫秒
     * @param date
     * @param value
     * @return Date
    * @author mshi
     */
    public static final Date setMilliSecond(Date date, int value) {
       return set(date, Calendar.MILLISECOND, value);
    }  
    
    /**
     * 设置指定的时间量
     * @param date
     * @param field
     * @param value
     * @return Date
    * @author mshi
     */
    public static final Date set(Date date, int field, int value){
       Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        cal.set(field, value);
        return cal.getTime();
    }
   
   /**
    * 设置日期为当月的最后一天
    * @param date
    * @return Date
    * @author mshi
    */
   public static final Date lastDate(Date date){
      return addDay(addMonth(setDay(date, 1), 1), -1);
   }
   
   /**
    * 设置日期为当月的第一天
    * @param date
    * @return Date
    * @author mshi
    */
   public static final Date firstDate(Date date){
      return setDay(date, 1);
   }
   
   /**
    * 是否是当月最后一天
    * @param date
    * @return boolean
    * @author mshi
    */
   public static final boolean isLastDate(Date date) {
      Date _date = date;
      Date lastDate = lastDate(_date);
      if (compareByDate(date, lastDate) == 0) {
         return true;
      }
      return false;
   }
   
   /**
    * 是否是当月第一天
    * @param date
    * @return boolean
    * @author mshi
    */
   public static final boolean isFirstDate(Date date) {
      Date _date = date;
      Date firstDate = firstDate(_date);
      if (compareByDate(date, firstDate) == 0) {
         return true;
      }
      return false;
   }
   
   /**
    * 是否是同一天
    * @param date1
    * @param date2
    * @return boolean
    * @author mshi
    */
   public static final boolean isSameDate(Date date1, Date date2) {
      if (compareByDate(getDateIgnoreTime(date1), getDateIgnoreTime(date2)) == 0) {
         return true;
      }
      return false;
   }
   
   /**
    * 是否是同一天月
    * @param date1
    * @param date2
    * @return boolean
    * @author mshi
    */
   public static boolean isSameMonth(Date date1, Date date2) {
      if (getMonth(date1) == getMonth(date2)) {
         return true;
      }
      return false;
   }
   
   /**
    * 是否是同一天年
    * @param date1
    * @param date2
    * @return boolean
    * @author mshi
    */
   public static boolean isSameYear(Date date1, Date date2) {
      if (getYear(date1) == getYear(date2)) {
         return true;
      }
      return false;
   }
   
    /**
     * 根据指定格式格式化时间
     * @param date
     * @param fmtString
     * @return String
    * @author mshi
     */
    public static final String format(Date date, String fmtString) {
      DateFormat format = new SimpleDateFormat(fmtString);
      return format.format(date);
   }
    
    /**
     * 格式格式化时间("yyyy-MM-dd")
     * @param date
     * @return String
    * @author mshi
     */
    public static final String formatDate(Date date) {
      if (null == date)
         return null;
      return format(date, "yyyy-MM-dd");
   }
    
    /**
     * 格式格式化时间("yyyy-MM-dd HH:mm:ss")
     * @param date
     * @return String
    * @author mshi
     */
    public static final String formatTime(Date date) {
      if (null == date)
         return null;
       return format(date, "yyyy-MM-dd HH:mm:ss");
   }
    
    /**
     * 根据指定格式解析时间
     * @param dateString
     * @param fmtString
     * @return Date
    * @author mshi
     */
   public static final Date parse(String dateString, String fmtString){
      Date date = null;
      try {
         DateFormat format = new SimpleDateFormat(fmtString);
         format.setLenient(false);
         date = format.parse(dateString);
      } catch (ParseException e) {
         logger.error("parse(String, String) parse error", e);
      }
      return date;
   }
   
    /**
     * 解析时间("yyyy-MM-dd")
     * @param dateString
     * @return Date
    * @author mshi
     */
   public static final Date parseDate(String dateString){
      return parse(dateString, "yyyy-MM-dd");
   }
   /**
    * 解析时间("yyyyMMdd")
    * @param dateString
    * @return Date
    * @author mshi
    */
   public static final Date parseDateString(String dateString){
      return parse(dateString, "yyyyMMdd");
   }

    /**
     * 解析时间("yyyy-MM-dd HH:mm:ss")
     * @param dateString
     * @return Date
    * @author mshi
     */
   public static final Date parseTime(String dateString){
      return parse(dateString, "yyyy-MM-dd HH:mm:ss");
   }
   
   /**
    * 根据年,月计算当前月份的最大天数
    * @param year
    * @param month
    * @return
    */
   public static int getLastDay(int year, int month) {
         int day = 1;
         Calendar cal = Calendar.getInstance();
         cal.set(year,month - 1,day);
         int last = cal.getActualMaximum(Calendar.DATE);
         return last;
     }
    /**
     * @param year 年份
     * @param month 月份
     * @param weekOfMonth 这个月的第几周
     * @param dayOfWeek 星期几
     * 例如:2016年4月,第二个星期,返回第二个星期的日期范围
     * System.out.println(weekMontoSun(2016, 04, 2, 1));
     * System.out.println(weekMontoSun(2016, 04, 2, 7));
     * @return
     */
   public static String weekMontoSun(int year,int month,int weekOfMonth,int dayOfWeek){
       Calendar c = Calendar.getInstance();
       c.set(year, month-1, 1); // x年 y月 1号
       int i_week_day = c.get(Calendar.DAY_OF_WEEK); //如果i_week_day =1 的话 实际上是周日
       int weekDay = 0;
       if(i_week_day == 1){ //dayOfWeek+1 就是星期几(星期日 为 1)
            weekDay = (weekOfMonth-1)*7 + dayOfWeek+1;
       }else{
             weekDay = 7-i_week_day+1 + (weekOfMonth-1)*7 + dayOfWeek +1;
       }
       c.set(Calendar.DATE, weekDay); //在当月1号的基础上加上相应的天数
       SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
       return sf.format(c.getTime());
    }
   
   /**
    * 计算当天是本月的第几个星期
    * @return
    */
   @SuppressWarnings("static-access")
   public static int getWeek() { 
         int week=0; 
         try { //获得当前日期 
            Calendar calendar = Calendar.getInstance(); //设置每周的第一天为星期一
            calendar.setFirstDayOfWeek(Calendar.MONDAY); //获得本月的第几个星期 
            week=calendar.get(calendar.DAY_OF_WEEK_IN_MONTH); 
            } catch (Exception e) { 
               e.printStackTrace(); 
            } 
             return week; 
      }
   /**
    * Date date  传入日期
    * 计算日期是本月的第几个星期
    * @return
    */
   @SuppressWarnings("static-access")
   public static int getWeek(Date date) { 
      int week=0; 
      try { //获得当前日期 
         Calendar cal=Calendar.getInstance();
         cal.setTime(date);
         Calendar calendar = cal; //设置每周的第一天为星期一
         calendar.setFirstDayOfWeek(Calendar.SUNDAY); //获得本月的第几个星期 
         week=calendar.get(calendar.DAY_OF_WEEK_IN_MONTH); 
      } catch (Exception e) { 
         e.printStackTrace(); 
      } 
      return week; 
   }

   /**
    * 日期的星期表示
    *
    * @param date 日期
    * @return 日期的星期表示(周一、周二、周三、周四、周五、周六、周日)
    */
   public static String date2WeekDay(Date date) {
      Calendar calendar = Calendar.getInstance();
      calendar.setTime(date);
      int weekDay = calendar.get(Calendar.DAY_OF_WEEK);
      String result;
      switch (weekDay) {
         case Calendar.MONDAY:
            result = "周一";
            break;
         case Calendar.TUESDAY:
            result = "周二";
            break;
         case Calendar.WEDNESDAY:
            result = "周三";
            break;
         case Calendar.THURSDAY:
            result = "周四";
            break;
         case Calendar.FRIDAY:
            result = "周五";
            break;
         case Calendar.SATURDAY:
            result = "周六";
            break;
         case Calendar.SUNDAY:
            result = "周日";
            break;
         default:
            result = "";
      }

      return result;
   }
   /**
    * 日期的星期表示
    *
    * @param date 日期
    * @return 日期的星期表示(周一、周二、周三、周四、周五、周六、周日)
    */
   public static int dateOfWeekDay(Date date) {
      Calendar calendar = Calendar.getInstance();
      calendar.setTime(date);
      int weekDay = calendar.get(Calendar.DAY_OF_WEEK);
      return weekDay;
   }

   /**
    * 将 20150101 格式的数字 转成 1月1日 星期一
    * 
    * @param dateNum
    * @return
    * @throws ParseException
    */
   public static String date2Week(Integer dateNum)
   {
      String result = "";
      SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
      sdf.setLenient(false);
      SimpleDateFormat sdf2 = new SimpleDateFormat("MM月dd日");
      Date strToDate = null;
      try
      {
         strToDate = sdf.parse(dateNum.toString());
      }
      catch (ParseException e)
      {
         e.printStackTrace();
      }
      Calendar c = Calendar.getInstance();
      c.setTime(strToDate);
      int dayForWeek = 0;
      if (c.get(Calendar.DAY_OF_WEEK) == 1)
      {
         dayForWeek = 7;
      }
      else
      {
         dayForWeek = c.get(Calendar.DAY_OF_WEEK) - 1;
      }
      switch (dayForWeek)
      {
      case 1:
         result = "周一";
         break;
      case 2:
         result = "周二";
         break;
      case 3:
         result = "周三";
         break;
      case 4:
         result = "周四";
         break;
      case 5:
         result = "周五";
         break;
      case 6:
         result = "周六";
         break;
      default:
         result = "周日";
         break;
      }
      result = sdf2.format(strToDate) + " " + result;
      return result;
   }

   /**
    * 将时间戳转换为yyyy-MM-dd HH:mm:ss
    * @param number  传入long 型时间戳
    * @return
    */
   public static String parseLongToDateTime(long number){
       SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");  
         
        return sdf.format(new Date(number));
        
   }

   /**
    * 将时间戳转换为yyyy-MM-dd HH:mm:ss
    * @param number  传入long 型时间戳
    * @return
    */
   public static String parseLongToDate(long number){
      SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");

      return sdf.format(new Date(number));

   }
   /**
    * 将时间戳转换为yyyy-MM-dd HH:mm:ss
    * @param number  传入long 型时间戳
    * @return
    */
   public static Date parseLongDate(long number){
      SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");

      return new Date(number);

   }

   /**
    * 将时间戳转换为yyyyMMdd
    * @param number  传入long 型时间戳
    * @return
    */
   public static String parseLongToInteger(long number){
      SimpleDateFormat sdf=new SimpleDateFormat("yyyyMMdd");

      return sdf.format(new Date(number));

   }

   public static void main(String[] args) {
      Date date = new Date();
      System.out.println(date);
      System.out.println(date.getTime());
      Date newDate = DateUtil.setMilliSecond(date, 999);
      System.out.println(newDate.getTime());
      newDate = DateUtil.setMinute(date, 50);
      System.out.println(newDate);

      System.out.println(date2WeekDay(new Date()));
   }
}
package com.hexiang.utils; /** * @(#)DateUtil.java * * * @author kidd * @version 1.00 2007/8/8 */ import java.util.*; import java.text.*; import java.sql.Timestamp; public class DateUtils { /** * 时间范围:年 */ public static final int YEAR = 1; /** * 时间范围:季度 */ public static final int QUARTER = 2; /** * 时间范围:月 */ public static final int MONTH = 3; /** * 时间范围:旬 */ public static final int TENDAYS = 4; /** * 时间范围:周 */ public static final int WEEK = 5; /** * 时间范围:日 */ public static final int DAY = 6; /* 基准时间 */ private Date fiducialDate = null; private Calendar cal = null; private DateUtils(Date fiducialDate) { if (fiducialDate != null) { this.fiducialDate = fiducialDate; } else { this.fiducialDate = new Date(System.currentTimeMillis()); } this.cal = Calendar.getInstance(); this.cal.setTime(this.fiducialDate); this.cal.set(Calendar.HOUR_OF_DAY, 0); this.cal.set(Calendar.MINUTE, 0); this.cal.set(Calendar.SECOND, 0); this.cal.set(Calendar.MILLISECOND, 0); this.fiducialDate = this.cal.getTime(); } /** * 获取DateHelper实例 * * @param fiducialDate * 基准时间 * @return Date */ public static DateUtils getInstance(Date fiducialDate) { return new DateUtils(fiducialDate); } /** * 获取DateHelper实例, 使用当前时间作为基准时间 * * @return Date */ public static DateUtils getInstance() { return new DateUtils(null); } /** * 获取年的第一天 * * @param offset * 偏移量 * @return Date */ public Date getFirstDayOfYear(int offset) { cal.setTime(this.fiducialDate); cal.set(Calendar.YEAR, cal.get(Calendar.YEAR) + offset); cal.set(Calendar.MONTH, Calendar.JANUARY); cal.set(Calendar.DAY_OF_MONTH, 1); return cal.getTime(); } /** * 获取年的最后一天 * * @param offset * 偏移量 * @return Date */ public Date getLastDayOfYear(int offset) { cal.setTime(this.fiducialDate); cal.set(Calendar.YEAR, cal.get(Calendar.YEAR) + offset); cal.set(Calendar.MONTH, Calendar.DECEMBER); cal.set(Calendar.DAY_OF_MONTH, 31); return cal.getTime(); } /** * 获取季度的第一天 * * @param offset * 偏移量 * @return Date */ public Date getFirstDayOfQuarter(int offset) { cal.setTime(this.fiducialDate); cal.add(Calendar.MONTH, offset * 3); int mon = cal.get(Calendar.MONTH); if (mon >= Calendar.JANUARY && mon = Calendar.APRIL && mon = Calendar.JULY && mon = Calendar.OCTOBER && mon = Calendar.JANUARY && mon = Calendar.APRIL && mon = Calendar.JULY && mon = Calendar.OCTOBER && mon = 21) { day = 21; } else if (day >= 11) { day = 11; } else { day = 1; } if (offset > 0) { day = day + 10 * offset; int monOffset = day / 30; day = day % 30; cal.add(Calendar.MONTH, monOffset); cal.set(Calendar.DAY_OF_MONTH, day); } else { int monOffset = 10 * offset / 30; int dayOffset = 10 * offset % 30; if ((day + dayOffset) > 0) { day = day + dayOffset; } else { monOffset = monOffset - 1; day = day - dayOffset - 10; } cal.add(Calendar.MONTH, monOffset); cal.set(Calendar.DAY_OF_MONTH, day); } return cal.getTime(); } /** * 获取旬的最后一天 * * @param offset * 偏移量 * @return Date */ public Date getLastDayOfTendays(int offset) { Date date = getFirstDayOfTendays(offset + 1); cal.setTime(date); cal.add(Calendar.DAY_OF_MONTH, -1); return cal.getTime(); } /** * 获取周的第一天(MONDAY) * * @param offset * 偏移量 * @return Date */ public Date getFirstDayOfWeek(int offset) { cal.setTime(this.fiducialDate); cal.add(Calendar.DAY_OF_MONTH, offset * 7); cal.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY); return cal.getTime(); } /** * 获取周的最后一天(SUNDAY) * * @param offset * 偏移量 * @return Date */ public Date getLastDayOfWeek(int offset) { cal.setTime(this.fiducialDate); cal.add(Calendar.DAY_OF_MONTH, offset * 7); cal.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY); cal.add(Calendar.DAY_OF_MONTH, 6); return cal.getTime(); } /** * 获取指定时间范围的第一天 * * @param dateRangeType * 时间范围类型 * @param offset * 偏移量 * @return Date */ public Date getFirstDate(int dateRangeType, int offset) { return null; } /** * 获取指定时间范围的最后一天 * * @param dateRangeType * 时间范围类型 * @param offset * 偏移量 * @return Date */ public Date getLastDate(int dateRangeType, int offset) { return null; } /** * 根据日历的规则,为基准时间添加指定日历字段的时间量 * * @param field * 日历字段, 使用Calendar类定义的日历字段常量 * @param offset * 偏移量 * @return Date */ public Date add(int field, int offset) { cal.setTime(this.fiducialDate); cal.add(field, offset); return cal.getTime(); } /** * 根据日历的规则,为基准时间添加指定日历字段的单个时间单元 * * @param field * 日历字段, 使用Calendar类定义的日历字段常量 * @param up * 指定日历字段的值的滚动方向。true:向上滚动 / false:向下滚动 * @return Date */ public Date roll(int field, boolean up) { cal.setTime(this.fiducialDate); cal.roll(field, up); return cal.getTime(); } /** * 把字符串转换为日期 * * @param dateStr * 日期字符串 * @param format * 日期格式 * @return Date */ public static Date strToDate(String dateStr, String format) { Date date = null; if (dateStr != null && (!dateStr.equals(""))) { DateFormat df = new SimpleDateFormat(format); try { date = df.parse(dateStr); } catch (ParseException e) { e.printStackTrace(); } } return date; } /** * 把字符串转换为日期,日期的格式为yyyy-MM-dd HH:ss * * @param dateStr * 日期字符串 * @return Date */ public static Date strToDate(String dateStr) { Date date = null; if (dateStr != null && (!dateStr.equals(""))) { if (dateStr.matches("\\d{4}-\\d{1,2}-\\d{1,2}")) { dateStr = dateStr + " 00:00"; } else if (dateStr.matches("\\d{4}-\\d{1,2}-\\d{1,2} \\d{1,2}")) { dateStr = dateStr + ":00"; } else { System.out.println(dateStr + " 格式不正确"); return null; } DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:ss"); try { date = df.parse(dateStr); } catch (ParseException e) { e.printStackTrace(); } } return date; } /** * 把日期转换为字符串 * * @param date * 日期实例 * @param format * 日期格式 * @return Date */ public static String dateToStr(Date date, String format) { return (date == null) ? "" : new SimpleDateFormat(format).format(date); } public static String dateToStr(Date date) { return (date == null) ? "" : new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(date); } /** * 取得当前日期 年-月-日 * * @return Date */ public static String getCurrentDate() { DateFormat f = new SimpleDateFormat("yyyy-MM-dd"); return f.format(Calendar.getInstance().getTime()); } public static void main(String[] args) { DateUtils dateHelper = DateUtils.getInstance(); /* Year */ for (int i = -5; i <= 5; i++) { System.out.println("FirstDayOfYear(" + i + ") = " + dateHelper.getFirstDayOfYear(i)); System.out.println("LastDayOfYear(" + i + ") = " + dateHelper.getLastDayOfYear(i)); } /* Quarter */ for (int i = -5; i <= 5; i++) { System.out.println("FirstDayOfQuarter(" + i + ") = " + dateHelper.getFirstDayOfQuarter(i)); System.out.println("LastDayOfQuarter(" + i + ") = " + dateHelper.getLastDayOfQuarter(i)); } /* Month */ for (int i = -5; i <= 5; i++) { System.out.println("FirstDayOfMonth(" + i + ") = " + dateHelper.getFirstDayOfMonth(i)); System.out.println("LastDayOfMonth(" + i + ") = " + dateHelper.getLastDayOfMonth(i)); } /* Week */ for (int i = -5; i <= 5; i++) { System.out.println("FirstDayOfWeek(" + i + ") = " + dateHelper.getFirstDayOfWeek(i)); System.out.println("LastDayOfWeek(" + i + ") = " + dateHelper.getLastDayOfWeek(i)); } /* Tendays */ for (int i = -5; i <= 5; i++) { System.out.println("FirstDayOfTendays(" + i + ") = " + dateHelper.getFirstDayOfTendays(i)); System.out.println("LastDayOfTendays(" + i + ") = " + dateHelper.getLastDayOfTendays(i)); } } /** * 取当前日期的字符串形式,"XXXX年XX月XX日" * * @return java.lang.String */ public static String getPrintDate() { String printDate = ""; Calendar calendar = Calendar.getInstance(); calendar.setTime(new Date()); printDate += calendar.get(Calendar.YEAR) + "年"; printDate += (calendar.get(Calendar.MONTH) + 1) + "月"; printDate += calendar.get(Calendar.DATE) + "日"; return printDate; } /** * 将指定的日期字符串转化为日期对象 * * @param dateStr * 日期字符串 * @return java.util.Date */ public static Date getDate(String dateStr, String format) { if (dateStr == null) { return new Date(); } if (format == null) { format = "yyyy-MM-dd"; } SimpleDateFormat sdf = new SimpleDateFormat(format); try { Date date = sdf.parse(dateStr); return date; } catch (Exception e) { return null; } } /** * 从指定Timestamp中得到相应的日期的字符串形式 日期"XXXX-XX-XX" * * @param dateTime * @return 、String */ public static String getDateFromDateTime(Timestamp dateTime) { SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); return sdf.format(dateTime).toString(); } /** * 得到当前时间 return java.sql.Timestamp * * @return Timestamp */ public static Timestamp getNowTimestamp() { long curTime = System.currentTimeMillis(); return new Timestamp(curTime); } }
package com.hexiang.utils; import java.text.SimpleDateFormat; import java.util.*; public class CalendarUtil { public static void main(String args[]) { System.out.println("First day of week is : " + new SimpleDateFormat("yyyy-MM-dd") .format(getFirstDateByWeek(new Date()))); System.out.println("Last day of week is : " + new SimpleDateFormat("yyyy-MM-dd") .format(getLastDateByWeek(new Date()))); System.out.println("First day of month is : " + new SimpleDateFormat("yyyy-MM-dd") .format(getFirstDateByMonth(new Date()))); System.out.println("Last day of month is : " + new SimpleDateFormat("yyyy-MM-dd") .format(getLastDateByMonth(new Date()))); } /** * 获得所在星期的第一天 */ public static Date getFirstDateByWeek(Date date) { Calendar now = Calendar.getInstance(); now.setTime(date); int today = now.get(Calendar.DAY_OF_WEEK); int first_day_of_week = now.get(Calendar.DATE) + 2 - today; // 星期一 now.set(Calendar.DATE, first_day_of_week); return now.getTime(); } /** * 获得所在星期的最后一天 */ public static Date getLastDateByWeek(Date date) { Calendar now = Calendar.getInstance(); now.setTime(date); int today = now.get(Calendar.DAY_OF_WEEK); int first_day_of_week = now.get(Calendar.DATE) + 2 - today; // 星期一 int last_day_of_week = first_day_of_week + 6; // 星期日 now.set(Calendar.DATE, last_day_of_week); return now.getTime(); } /** * 获得所在月份的最后一天 * @param 当前月份所在的时间 * @return 月份的最后一天 */ public static Date getLastDateByMonth(Date date) { Calendar now = Calendar.getInstance(); now.setTime(date); now.set(Calendar.MONTH, now.get(Calendar.MONTH) + 1); now.set(Calendar.DATE, 1); now.set(Calendar.DATE, now.get(Calendar.DATE) - 1); now.set(Calendar.HOUR, 11); now.set(Calendar.MINUTE, 59); now.set(Calendar.SECOND, 59); return now.getTime(); } /** * 获得所在月份的第一天 * @param 当前月份所在的时间 * @return 月份的第一天 */ public static Date getFirstDateByMonth(Date date) { Calendar now = Calendar.getInstance(); now.setTime(date); now.set(Calendar.DATE, 0); now.set(Calendar.HOUR, 12); now.set(Calendar.MINUTE, 0); now.set(Calendar.SECOND, 0); return now.getTime(); } }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值