欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

java日期处理工具类

程序员文章站 2024-03-12 09:38:14
本文针对日期处理进行学习使用,主要分为两部分,下面为大家具体介绍一下 第一部分:日期处理基础知识 date 类 作用:最主要的作用就是获得当前时间 将日期转换为标准...

本文针对日期处理进行学习使用,主要分为两部分,下面为大家具体介绍一下

第一部分:日期处理基础知识

date 类
作用:最主要的作用就是获得当前时间
将日期转换为标准格式

date date = new date();
simpledateformat sdf = new simpledateformat("yyyy-mm-dd hh:mm:ss");
string str = sdf.format(date);
system.out.println(“2015-10-16 14:59:52”);

将string转换为date类型

string day = "2014-6-5 10:30:30";
simpledateformat d2 = new simpledateformat("yyyy-mm-dd hh:mm:ss");
date date2 = d2.parse(day);
system.out.println(“thu jun 05 10:30:30 cst 2014”);

calendar 类的应用

java.util.calendar 类是一个抽象类,可以通过调用 getinstance() 静态方法获取一个 calendar 对象,此对象已由当前日期时间初始化,即默认代表当前时间

 calendar c = calendar.getinstance();
int year = c.get(calender.year);
int month= c.get(calender.month)+1; //获取月份,0表示1月份
int day = c.get(calender.day_of_month);
int hour= c.get(calender.hour_of_day);
int minute= c.get(calender.minute);
int second = c.get(calender.second);

比较2个时间相差的月份

simpledateformat format = new simpledateformat("yyyy-mm-dd hh:mm:ss");
datetime d1 = new datetime(format.parse("2016-10-31 00:00:00"));
datetime d2 = new datetime(format.parse("2015-1-31 00:00:00"));
system.out.println(math.abs(months.monthsbetween(d1,d2).getmonths()));

第二部分:日期处理工具类

package com.analysys.website.control;
 
import java.text.parseexception;
import java.text.parseposition;
import java.text.simpledateformat;
import java.util.calendar;
import java.util.date;
import java.util.gregoriancalendar;
 
import org.apache.commons.lang.stringutils;
import org.apache.log4j.logger;
 
/** 
 * 日期处理工具类 
 * @author dylan_xu 
 * @date mar 11, 2012 
 * @modified by 
 * @modified date 
 * @since jdk1.6 
 * @see com.util.dateutil 
 */ 
  
public class dateutil { 
  // ~ static fields/initializers 
  // ============================================= 
  
  private static logger logger = logger.getlogger(dateutil.class); 
  private static string defaultdatepattern = null; 
  private static string timepattern = "hh:mm"; 
  private static calendar cale = calendar.getinstance(); 
  public static final string ts_format = dateutil.getdatepattern() + " hh:mm:ss.s"; 
  /** 日期格式yyyy-mm字符串常量 */ 
  private static final string month_format = "yyyy-mm"; 
  /** 日期格式yyyy-mm-dd字符串常量 */ 
  private static final string date_format = "yyyy-mm-dd"; 
  /** 日期格式hh:mm:ss字符串常量 */ 
  private static final string hour_format = "hh:mm:ss"; 
  /** 日期格式yyyy-mm-dd hh:mm:ss字符串常量 */ 
  private static final string datetime_format = "yyyy-mm-dd hh:mm:ss"; 
  /** 某天开始时分秒字符串常量 00:00:00 */ 
  private static final string day_begin_string_hhmmss = " 00:00:00"; 
  /** 某天结束时分秒字符串常量 23:59:59 */ 
  public static final string day_end_string_hhmmss = " 23:59:59"; 
  private static simpledateformat sdf_date_format = new simpledateformat(date_format); 
  private static simpledateformat sdf_hour_format = new simpledateformat(hour_format); 
  private static simpledateformat sdf_datetime_format = new simpledateformat(datetime_format); 
    
  
  // ~ methods 
  // ================================================================ 
  
  public dateutil() { 
  } 
  
  /** 
   * 获得服务器当前日期及时间,以格式为:yyyy-mm-dd hh:mm:ss的日期字符串形式返回 
   * @author dylan_xu 
   * @date mar 11, 2012 
   * @return 
   */ 
  public static string getdatetime() { 
    try { 
      return sdf_datetime_format.format(cale.gettime()); 
    } catch (exception e) { 
      logger.debug("dateutil.getdatetime():" + e.getmessage()); 
      return ""; 
    } 
  } 
  
  /** 
   * 获得服务器当前日期,以格式为:yyyy-mm-dd的日期字符串形式返回 
   * @author dylan_xu 
   * @date mar 11, 2012 
   * @return 
   */ 
  public static string getdate() { 
    try { 
      return sdf_date_format.format(cale.gettime()); 
    } catch (exception e) { 
      logger.debug("dateutil.getdate():" + e.getmessage()); 
      return ""; 
    } 
  } 
  
  /** 
   * 获得服务器当前时间,以格式为:hh:mm:ss的日期字符串形式返回 
   * @author dylan_xu 
   * @date mar 11, 2012 
   * @return 
   */ 
  public static string gettime() { 
    string temp = " "; 
    try { 
      temp += sdf_hour_format.format(cale.gettime()); 
      return temp; 
    } catch (exception e) { 
      logger.debug("dateutil.gettime():" + e.getmessage()); 
      return ""; 
    } 
  } 
  
  /** 
   * 统计时开始日期的默认值 
   * @author dylan_xu 
   * @date mar 11, 2012 
   * @return 
   */ 
  public static string getstartdate() { 
    try { 
      return getyear() + "-01-01"; 
    } catch (exception e) { 
      logger.debug("dateutil.getstartdate():" + e.getmessage()); 
      return ""; 
    } 
  } 
  
  /** 
   * 统计时结束日期的默认值 
   * @author dylan_xu 
   * @date mar 11, 2012 
   * @return 
   */ 
  public static string getenddate() { 
    try { 
      return getdate(); 
    } catch (exception e) { 
      logger.debug("dateutil.getenddate():" + e.getmessage()); 
      return ""; 
    } 
  } 
  
  /** 
   * 获得服务器当前日期的年份 
   * @author dylan_xu 
   * @date mar 11, 2012 
   * @return 
   */ 
  public static string getyear() { 
    try { 
      return string.valueof(cale.get(calendar.year)); 
    } catch (exception e) { 
      logger.debug("dateutil.getyear():" + e.getmessage()); 
      return ""; 
    } 
  } 
  
  /** 
   * 获得服务器当前日期的月份 
   * @author dylan_xu 
   * @date mar 11, 2012 
   * @return 
   */ 
  public static string getmonth() { 
    try { 
      java.text.decimalformat df = new java.text.decimalformat(); 
      df.applypattern("00;00"); 
      return df.format((cale.get(calendar.month) + 1)); 
    } catch (exception e) { 
      logger.debug("dateutil.getmonth():" + e.getmessage()); 
      return ""; 
    } 
  } 
  
  /** 
   * 获得服务器在当前月中天数 
   * @author dylan_xu 
   * @date mar 11, 2012 
   * @return 
   */ 
  public static string getday() { 
    try { 
      return string.valueof(cale.get(calendar.day_of_month)); 
    } catch (exception e) { 
      logger.debug("dateutil.getday():" + e.getmessage()); 
      return ""; 
    } 
  } 
  
  /** 
   * 比较两个日期相差的天数 
   * @author dylan_xu 
   * @date mar 11, 2012 
   * @param date1 
   * @param date2 
   * @return 
   */ 
  public static int getmargin(string date1, string date2) { 
    int margin; 
    try { 
      parseposition pos = new parseposition(0); 
      parseposition pos1 = new parseposition(0); 
      date dt1 = sdf_date_format.parse(date1, pos); 
      date dt2 = sdf_date_format.parse(date2, pos1); 
      long l = dt1.gettime() - dt2.gettime(); 
      margin = (int) (l / (24 * 60 * 60 * 1000)); 
      return margin; 
    } catch (exception e) { 
      logger.debug("dateutil.getmargin():" + e.tostring()); 
      return 0; 
    } 
  } 
  
  /** 
   * 比较两个日期相差的天数 
   * @author dylan_xu 
   * @date mar 11, 2012 
   * @param date1 
   * @param date2 
   * @return 
   */ 
  public static double getdoublemargin(string date1, string date2) { 
    double margin; 
    try { 
      parseposition pos = new parseposition(0); 
      parseposition pos1 = new parseposition(0); 
      date dt1 = sdf_datetime_format.parse(date1, pos); 
      date dt2 = sdf_datetime_format.parse(date2, pos1); 
      long l = dt1.gettime() - dt2.gettime(); 
      margin = (l / (24 * 60 * 60 * 1000.00)); 
      return margin; 
    } catch (exception e) { 
      logger.debug("dateutil.getmargin():" + e.tostring()); 
      return 0; 
    } 
  } 
  
  /** 
   * 比较两个日期相差的月数 
   * @author dylan_xu 
   * @date mar 11, 2012 
   * @param date1 
   * @param date2 
   * @return 
   */ 
  public static int getmonthmargin(string date1, string date2) { 
    int margin; 
    try { 
      margin = (integer.parseint(date2.substring(0, 4)) - integer.parseint(date1.substring(0, 4))) * 12; 
      margin += (integer.parseint(date2.substring(4, 7).replaceall("-0", 
          "-")) - integer.parseint(date1.substring(4, 7).replaceall("-0", "-"))); 
      return margin; 
    } catch (exception e) { 
      logger.debug("dateutil.getmargin():" + e.tostring()); 
      return 0; 
    } 
  } 
  
  /** 
   * 返回日期加x天后的日期 
   * @author dylan_xu 
   * @date mar 11, 2012 
   * @param date 
   * @param i 
   * @return 
   */ 
  public static string addday(string date, int i) { 
    try { 
      gregoriancalendar gcal = new gregoriancalendar( 
          integer.parseint(date.substring(0, 4)),  
          integer.parseint(date.substring(5, 7)) - 1,  
          integer.parseint(date.substring(8, 10))); 
      gcal.add(gregoriancalendar.date, i); 
      return sdf_date_format.format(gcal.gettime()); 
    } catch (exception e) { 
      logger.debug("dateutil.addday():" + e.tostring()); 
      return getdate(); 
    } 
  } 
  
  /** 
   * 返回日期加x月后的日期 
   * @author dylan_xu 
   * @date mar 11, 2012 
   * @param date 
   * @param i 
   * @return 
   */ 
  public static string addmonth(string date, int i) { 
    try { 
      gregoriancalendar gcal = new gregoriancalendar( 
          integer.parseint(date.substring(0, 4)),  
          integer.parseint(date.substring(5, 7)) - 1,  
          integer.parseint(date.substring(8, 10))); 
      gcal.add(gregoriancalendar.month, i); 
      return sdf_date_format.format(gcal.gettime()); 
    } catch (exception e) { 
      logger.debug("dateutil.addmonth():" + e.tostring()); 
      return getdate(); 
    } 
  } 
  
  /** 
   * 返回日期加x年后的日期 
   * @author dylan_xu 
   * @date mar 11, 2012 
   * @param date 
   * @param i 
   * @return 
   */ 
  public static string addyear(string date, int i) { 
    try { 
      gregoriancalendar gcal = new gregoriancalendar( 
          integer.parseint(date.substring(0, 4)),  
          integer.parseint(date.substring(5, 7)) - 1,  
          integer.parseint(date.substring(8, 10))); 
      gcal.add(gregoriancalendar.year, i); 
      return sdf_date_format.format(gcal.gettime()); 
    } catch (exception e) { 
      logger.debug("dateutil.addyear():" + e.tostring()); 
      return ""; 
    } 
  } 
  
  /** 
   * 返回某年某月中的最大天 
   * @author dylan_xu 
   * @date mar 11, 2012 
   * @param year 
   * @param month 
   * @return 
   */ 
  public static int getmaxday(int iyear, int imonth) { 
    int day = 0; 
    try { 
      if (imonth == 1 || imonth == 3 || imonth == 5 || imonth == 7 
          || imonth == 8 || imonth == 10 || imonth == 12) { 
        day = 31; 
      } else if (imonth == 4 || imonth == 6 || imonth == 9 || imonth == 11) { 
        day = 30; 
      } else if ((0 == (iyear % 4)) && (0 != (iyear % 100)) || (0 == (iyear % 400))) { 
        day = 29; 
      } else { 
        day = 28; 
      } 
      return day; 
    } catch (exception e) { 
      logger.debug("dateutil.getmonthday():" + e.tostring()); 
      return 1; 
    } 
  } 
  
  /** 
   * 格式化日期 
   * @author dylan_xu 
   * @date mar 11, 2012 
   * @param orgdate 
   * @param type 
   * @param span 
   * @return 
   */ 
  @suppresswarnings("static-access") 
  public string rolldate(string orgdate, int type, int span) { 
    try { 
      string temp = ""; 
      int iyear, imonth, iday; 
      int ipos = 0; 
      char seperater = '-'; 
      if (orgdate == null || orgdate.length() < 6) { 
        return ""; 
      } 
  
      ipos = orgdate.indexof(seperater); 
      if (ipos > 0) { 
        iyear = integer.parseint(orgdate.substring(0, ipos)); 
        temp = orgdate.substring(ipos + 1); 
      } else { 
        iyear = integer.parseint(orgdate.substring(0, 4)); 
        temp = orgdate.substring(4); 
      } 
  
      ipos = temp.indexof(seperater); 
      if (ipos > 0) { 
        imonth = integer.parseint(temp.substring(0, ipos)); 
        temp = temp.substring(ipos + 1); 
      } else { 
        imonth = integer.parseint(temp.substring(0, 2)); 
        temp = temp.substring(2); 
      } 
  
      imonth--; 
      if (imonth < 0 || imonth > 11) { 
        imonth = 0; 
      } 
  
      iday = integer.parseint(temp); 
      if (iday < 1 || iday > 31) 
        iday = 1; 
  
      calendar orgcale = calendar.getinstance(); 
      orgcale.set(iyear, imonth, iday); 
      temp = this.rolldate(orgcale, type, span); 
      return temp; 
    } catch (exception e) { 
      return ""; 
    } 
  } 
  
  public static string rolldate(calendar cal, int type, int span) { 
    try { 
      string temp = ""; 
      calendar rolcale; 
      rolcale = cal; 
      rolcale.add(type, span); 
      temp = sdf_date_format.format(rolcale.gettime()); 
      return temp; 
    } catch (exception e) { 
      return ""; 
    } 
  } 
  
  /** 
   * 返回默认的日期格式 
   * @author dylan_xu 
   * @date mar 11, 2012 
   * @return 
   */ 
  public static synchronized string getdatepattern() { 
    defaultdatepattern = "yyyy-mm-dd"; 
    return defaultdatepattern; 
  } 
  
  /** 
   * 将指定日期按默认格式进行格式代化成字符串后输出如:yyyy-mm-dd 
   * @author dylan_xu 
   * @date mar 11, 2012 
   * @param adate 
   * @return 
   */ 
  public static final string getdate(date adate) { 
    simpledateformat df = null; 
    string returnvalue = ""; 
    if (adate != null) { 
      df = new simpledateformat(getdatepattern()); 
      returnvalue = df.format(adate); 
    } 
    return (returnvalue); 
  } 
  
  /** 
   * 取得给定日期的时间字符串,格式为当前默认时间格式 
   * @author dylan_xu 
   * @date mar 11, 2012 
   * @param thetime 
   * @return 
   */ 
  public static string gettimenow(date thetime) { 
    return getdatetime(timepattern, thetime); 
  } 
  
  /** 
   * 取得当前时间的calendar日历对象 
   * @author dylan_xu 
   * @date mar 11, 2012 
   * @return 
   * @throws parseexception 
   */ 
  public calendar gettoday() throws parseexception { 
    date today = new date(); 
    simpledateformat df = new simpledateformat(getdatepattern()); 
    string todayasstring = df.format(today); 
    calendar cal = new gregoriancalendar(); 
    cal.settime(convertstringtodate(todayasstring)); 
    return cal; 
  } 
  
  /** 
   * 将日期类转换成指定格式的字符串形式 
   * @author dylan_xu 
   * @date mar 11, 2012 
   * @param amask 
   * @param adate 
   * @return 
   */ 
  public static final string getdatetime(string amask, date adate) { 
    simpledateformat df = null; 
    string returnvalue = ""; 
  
    if (adate == null) { 
      logger.error("adate is null!"); 
    } else { 
      df = new simpledateformat(amask); 
      returnvalue = df.format(adate); 
    } 
    return (returnvalue); 
  } 
  
  /** 
   * 将指定的日期转换成默认格式的字符串形式 
   * @author dylan_xu 
   * @date mar 11, 2012 
   * @param adate 
   * @return 
   */ 
  public static final string convertdatetostring(date adate) { 
    return getdatetime(getdatepattern(), adate); 
  } 
  
  /** 
   * 将日期字符串按指定格式转换成日期类型 
   * @author dylan_xu 
   * @date mar 11, 2012 
   * @param amask 指定的日期格式,如:yyyy-mm-dd 
   * @param strdate 待转换的日期字符串 
   * @return 
   * @throws parseexception 
   */ 
  public static final date convertstringtodate(string amask, string strdate) 
      throws parseexception { 
    simpledateformat df = null; 
    date date = null; 
    df = new simpledateformat(amask); 
  
    if (logger.isdebugenabled()) { 
      logger.debug("converting '" + strdate + "' to date with mask '" + amask + "'"); 
    } 
    try { 
      date = df.parse(strdate); 
    } catch (parseexception pe) { 
      logger.error("parseexception: " + pe); 
      throw pe; 
    } 
    return (date); 
  } 
  
  /** 
   * 将日期字符串按默认格式转换成日期类型 
   * @author dylan_xu 
   * @date mar 11, 2012 
   * @param strdate 
   * @return 
   * @throws parseexception 
   */ 
  public static date convertstringtodate(string strdate) 
      throws parseexception { 
    date adate = null; 
  
    try { 
      if (logger.isdebugenabled()) { 
        logger.debug("converting date with pattern: " + getdatepattern()); 
      } 
      adate = convertstringtodate(getdatepattern(), strdate); 
    } catch (parseexception pe) { 
      logger.error("could not convert '" + strdate + "' to a date, throwing exception"); 
      throw new parseexception(pe.getmessage(), pe.geterroroffset()); 
    } 
    return adate; 
  } 
  
  /** 
   * 返回一个java简单类型的日期字符串 
   * @author dylan_xu 
   * @date mar 11, 2012 
   * @return 
   */ 
  public static string getsimpledateformat() { 
    simpledateformat formatter = new simpledateformat(); 
    string ndatetime = formatter.format(new date()); 
    return ndatetime; 
  } 
    
  /** 
   * 将指定字符串格式的日期与当前时间比较 
   * @author dylan 
   * @date feb 17, 2012 
   * @param strdate 需要比较时间 
   * @return 
   *   <p> 
   *   int code 
   *   <ul> 
   *   <li>-1 当前时间 < 比较时间 </li> 
   *   <li> 0 当前时间 = 比较时间 </li> 
   *   <li>>=1当前时间 > 比较时间 </li> 
   *   </ul> 
   *   </p> 
   */ 
  public static int comparetocurtime (string strdate) { 
    if (stringutils.isblank(strdate)) { 
      return -1; 
    } 
    date curtime = cale.gettime(); 
    string strcurtime = null; 
    try { 
      strcurtime = sdf_datetime_format.format(curtime); 
    } catch (exception e) { 
      if (logger.isdebugenabled()) { 
        logger.debug("[could not format '" + strdate + "' to a date, throwing exception:" + e.getlocalizedmessage() + "]"); 
      } 
    } 
    if (stringutils.isnotblank(strcurtime)) { 
      return strcurtime.compareto(strdate); 
    } 
    return -1; 
  } 
    
  /** 
   * 为查询日期添加最小时间 
   * 
   * @param 目标类型date 
   * @param 转换参数date 
   * @return 
   */ 
  @suppresswarnings("deprecation") 
  public static date addstarttime(date param) { 
    date date = param; 
    try { 
      date.sethours(0); 
      date.setminutes(0); 
      date.setseconds(0); 
      return date; 
    } catch (exception ex) { 
      return date; 
    } 
  } 
  
  /** 
   * 为查询日期添加最大时间 
   * 
   * @param 目标类型date 
   * @param 转换参数date 
   * @return 
   */ 
  @suppresswarnings("deprecation") 
  public static date addendtime(date param) { 
    date date = param; 
    try { 
      date.sethours(23); 
      date.setminutes(59); 
      date.setseconds(0); 
      return date; 
    } catch (exception ex) { 
      return date; 
    } 
  } 
  
  /** 
   * 返回系统现在年份中指定月份的天数 
   * 
   * @param 月份month 
   * @return 指定月的总天数 
   */ 
  @suppresswarnings("deprecation") 
  public static string getmonthlastday(int month) { 
    date date = new date(); 
    int[][] day = { { 0, 30, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }, 
        { 0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 } }; 
    int year = date.getyear() + 1900; 
    if (year % 4 == 0 && year % 100 != 0 || year % 400 == 0) { 
      return day[1][month] + ""; 
    } else { 
      return day[0][month] + ""; 
    } 
  } 
  
  /** 
   * 返回指定年份中指定月份的天数 
   * 
   * @param 年份year 
   * @param 月份month 
   * @return 指定月的总天数 
   */ 
  public static string getmonthlastday(int year, int month) { 
    int[][] day = { { 0, 30, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }, 
        { 0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 } }; 
    if (year % 4 == 0 && year % 100 != 0 || year % 400 == 0) { 
      return day[1][month] + ""; 
    } else { 
      return day[0][month] + ""; 
    } 
  } 
  
  /** 
   * 判断是平年还是闰年 
   * @author dylan_xu 
   * @date mar 11, 2012 
   * @param year 
   * @return 
   */ 
  public static boolean isleapyear(int year) { 
    if ((year % 4 == 0 && year % 100 != 0) || (year % 400) == 0) { 
      return true; 
    } else { 
      return false; 
    } 
  } 
  
  /** 
   * 取得当前时间的日戳 
   * @author dylan_xu 
   * @date mar 11, 2012 
   * @return 
   */ 
  @suppresswarnings("deprecation") 
  public static string gettimestamp() { 
    date date = cale.gettime(); 
    string timestamp = "" + (date.getyear() + 1900) + date.getmonth() 
        + date.getdate() + date.getminutes() + date.getseconds() 
        + date.gettime(); 
    return timestamp; 
  } 
  
  /** 
   * 取得指定时间的日戳 
   * 
   * @return 
   */ 
  @suppresswarnings("deprecation") 
  public static string gettimestamp(date date) { 
    string timestamp = "" + (date.getyear() + 1900) + date.getmonth() 
        + date.getdate() + date.getminutes() + date.getseconds() 
        + date.gettime(); 
    return timestamp; 
  } 
  
  public static void main(string[] args) { 
    system.out.println(getyear() + "|" + getmonth() + "|" + getdate()); 
  } 
} 

以上就是本文的全部内容,希望对大家的学习有所帮助。