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

Java日期工具类DateUtils实例详解

程序员文章站 2023-12-04 10:16:58
在项目开发中,日期是我们必不可少的的一部分,本文将总结代码开发中的关于日期常用的一些方法,以方便自己后期使用。下面直接上菜了: package com.exa...

在项目开发中,日期是我们必不可少的的一部分,本文将总结代码开发中的关于日期常用的一些方法,以方便自己后期使用。下面直接上菜了:

package com.example.util; 
 
import java.text.parseexception; 
import java.text.simpledateformat; 
import java.util.arraylist; 
import java.util.calendar; 
import java.util.date; 
import java.util.list; 
 
/** 
 * 日期常用方法 
 * 
 * @author 
 * 
 */ 
public class dateutils { 
 
  /** 
   * 常用变量 
   */ 
  public static final string date_format_full = "yyyy-mm-dd hh:mm:ss"; 
  public static final string date_format_ymd = "yyyy-mm-dd"; 
  public static final string date_format_hms = "hh:mm:ss"; 
  public static final string date_format_hm = "hh:mm"; 
  public static final string date_format_ymdhm = "yyyy-mm-dd hh:mm"; 
  public static final string date_format_ymdhms = "yyyymmddhhmmss"; 
  public static final long one_day_mills = 3600000 * 24; 
  public static final int week_days = 7; 
  private static final int datelength = date_format_ymdhm.length(); 
   
   
  /** 
   * 日期转换为制定格式字符串 
   * 
   * @param time 
   * @param format 
   * @return 
   */ 
  public static string formatdatetostring(date time, string format) { 
    simpledateformat sdf = new simpledateformat(format); 
    return sdf.format(time); 
  } 
 
  /** 
   * 字符串转换为制定格式日期 
   * (注意:当你输入的日期是2014-12-21 12:12,format对应的应为yyyy-mm-dd hh:mm 
   * 否则异常抛出) 
   * @param date 
   * @param format 
   * @return 
   * @throws parseexception 
   *       @ 
   */ 
  public static date formatstringtodate(string date, string format) { 
    simpledateformat sdf = new simpledateformat(format); 
    try { 
      return sdf.parse(date); 
    } catch (parseexception ex) { 
      ex.printstacktrace(); 
      throw new runtimeexception(ex.tostring()); 
    } 
  } 
 
  /** 
   * 判断一个日期是否属于两个时段内 
   * @param time 
   * @param timerange 
   * @return 
   */ 
  public static boolean istimeinrange(date time, date[] timerange) { 
    return (!time.before(timerange[0]) && !time.after(timerange[1])); 
  } 
 
  /** 
   * 从完整的时间截取精确到分的时间 
   * 
   * @param fulldatestr 
   * @return 
   */ 
  public static string getdatetominute(string fulldatestr) { 
    return fulldatestr == null ? null 
        : (fulldatestr.length() >= datelength ? fulldatestr.substring( 
            0, datelength) : fulldatestr); 
  } 
 
  /** 
   * 返回指定年度的所有周。list中包含的是string[2]对象 string[0]本周的开始日期,string[1]是本周的结束日期。 
   * 日期的格式为yyyy-mm-dd 每年的第一个周,必须包含星期一且是完整的七天。 
   * 例如:2009年的第一个周开始日期为2009-01-05,结束日期为2009-01-11。 星期一在哪一年,那么包含这个星期的周就是哪一年的周。 
   * 例如:2008-12-29是星期一,2009-01-04是星期日,哪么这个周就是2008年度的最后一个周。 
   * 
   * @param year 
   *      格式 yyyy ,必须大于1900年度 小于9999年 
   * @return @ 
   */ 
  public static list<string[]> getweeksbyyear(final int year) { 
    int weeks = getweeknumofyear(year); 
    list<string[]> result = new arraylist<string[]>(weeks); 
    int start = 1; 
    int end = 7; 
    for (int i = 1; i <= weeks; i++) { 
      string[] tempweek = new string[2]; 
      tempweek[0] = getdatefordayofweek(year, i, start); 
      tempweek[1] = getdatefordayofweek(year, i, end); 
      result.add(tempweek); 
    } 
    return result; 
  } 
 
  /** 
   * 计算指定年、周的上一年、周 
   * 
   * @param year 
   * @param week 
   * @return @ 
   */ 
  public static int[] getlastyearweek(int year, int week) { 
    if (week <= 0) { 
      throw new illegalargumentexception("周序号不能小于1!!"); 
    } 
    int[] result = { week, year }; 
    if (week == 1) { 
      // 上一年 
      result[1] -= 1; 
      // 最后一周 
      result[0] = getweeknumofyear(result[1]); 
    } else { 
      result[0] -= 1; 
    } 
    return result; 
  } 
 
  /** 
   * 下一个[周,年] 
   * 
   * @param year 
   * @param week 
   * @return @ 
   */ 
  public static int[] getnextyearweek(int year, int week) { 
    if (week <= 0) { 
      throw new illegalargumentexception("周序号不能小于1!!"); 
    } 
    int[] result = { week, year }; 
    int weeks = getweeknumofyear(year); 
    if (week == weeks) { 
      // 下一年 
      result[1] += 1; 
      // 第一周 
      result[0] = 1; 
    } else { 
      result[0] += 1; 
    } 
    return result; 
  } 
 
  /** 
   * 计算指定年度共有多少个周。(从周一开始) 
   * 
   * @param year 
   * @return @ 
   */ 
  public static int getweeknumofyear(final int year) { 
    return getweeknumofyear(year, calendar.monday); 
  } 
 
  /** 
   * 计算指定年度共有多少个周。 
   * 
   * @param year 
   *      yyyy 
   * @return @ 
   */ 
  public static int getweeknumofyear(final int year, int firstdayofweek) { 
    // 每年至少有52个周 ,最多有53个周。 
    int minweeks = 52; 
    int maxweeks = 53; 
    int result = minweeks; 
    int sindex = 4; 
    string date = getdatefordayofweek(year, maxweeks, firstdayofweek); 
    // 判断年度是否相符,如果相符说明有53个周。 
    if (date.substring(0, sindex).equals(year)) { 
      result = maxweeks; 
    } 
    return result; 
  } 
 
  public static int getweeksofweekyear(final int year) { 
    calendar cal = calendar.getinstance(); 
    cal.setfirstdayofweek(calendar.monday); 
    cal.setminimaldaysinfirstweek(week_days); 
    cal.set(calendar.year, year); 
    return cal.getweeksinweekyear(); 
  } 
 
  /** 
   * 获取指定年份的第几周的第几天对应的日期yyyy-mm-dd(从周一开始) 
   * 
   * @param year 
   * @param weekofyear 
   * @param dayofweek 
   * @return yyyy-mm-dd 格式的日期 @ 
   */ 
  public static string getdatefordayofweek(int year, int weekofyear, 
      int dayofweek) { 
    return getdatefordayofweek(year, weekofyear, dayofweek, calendar.monday); 
  } 
 
  /** 
   * 获取指定年份的第几周的第几天对应的日期yyyy-mm-dd,指定周几算一周的第一天(firstdayofweek) 
   * 
   * @param year 
   * @param weekofyear 
   * @param dayofweek 
   * @param firstdayofweek 
   *      指定周几算一周的第一天 
   * @return yyyy-mm-dd 格式的日期 
   */ 
  public static string getdatefordayofweek(int year, int weekofyear, 
      int dayofweek, int firstdayofweek) { 
    calendar cal = calendar.getinstance(); 
    cal.setfirstdayofweek(firstdayofweek); 
    cal.set(calendar.day_of_week, dayofweek); 
    cal.setminimaldaysinfirstweek(week_days); 
    cal.set(calendar.year, year); 
    cal.set(calendar.week_of_year, weekofyear); 
    return formatdatetostring(cal.gettime(), date_format_ymd); 
  } 
 
  /** 
   * 获取指定日期星期几 
   * 
   * @param datetime 
   * @throws parseexception 
   *       @ 
   */ 
  public static int getweekofdate(string datetime) throws parseexception { 
    calendar cal = calendar.getinstance(); 
    cal.setfirstdayofweek(calendar.monday); 
    cal.setminimaldaysinfirstweek(week_days); 
    date date = formatstringtodate(datetime, date_format_ymd); 
    cal.settime(date); 
    return cal.get(calendar.day_of_week); 
 
  } 
 
  /** 
   * 计算某年某周内的所有日期(从周一开始 为每周的第一天) 
   * 
   * @param yearnum 
   * @param weeknum 
   * @return @ 
   */ 
  public static list<string> getweekdays(int yearnum, int weeknum) { 
    return getweekdays(yearnum, weeknum, calendar.monday); 
  } 
 
  /** 
   * 计算某年某周内的所有日期(七天) 
   * 
   * @param yearnum 
   * @param weeknum 
   * @return yyyy-mm-dd 格式的日期列表 
   */ 
  public static list<string> getweekdays(int year, int weekofyear, 
      int firstdayofweek) { 
    list<string> dates = new arraylist<string>(); 
    int dayofweek = firstdayofweek; 
    for (int i = 0; i < week_days; i++) { 
      dates.add(getdatefordayofweek(year, weekofyear, dayofweek++, 
          firstdayofweek)); 
    } 
    return dates; 
  } 
 
  /** 
   * 获取目标日期的上周、或本周、或下周的年、周信息 
   * 
   * @param querydate 
   *      传入的时间 
   * @param weekoffset 
   *      -1:上周 0:本周 1:下周 
   * @param firstdayofweek 
   *      每周以第几天为首日 
   * @return 
   * @throws parseexception 
   */ 
  public static int[] getweekandyear(string querydate, int weekoffset, 
      int firstdayofweek) throws parseexception { 
 
    date date = formatstringtodate(querydate, date_format_ymd); 
    calendar calendar = calendar.getinstance(); 
    calendar.settime(date); 
    calendar.setfirstdayofweek(firstdayofweek); 
    calendar.setminimaldaysinfirstweek(week_days); 
    int year = calendar.getweekyear(); 
    int week = calendar.get(calendar.week_of_year); 
    int[] result = { week, year }; 
    switch (weekoffset) { 
    case 1: 
      result = getnextyearweek(year, week); 
      break; 
    case -1: 
      result = getlastyearweek(year, week); 
      break; 
    default: 
      break; 
    } 
    return result; 
  } 
 
  /** 
   * 计算个两日期的天数 
   * 
   * @param startdate 
   *      开始日期字串 
   * @param enddate 
   *      结束日期字串 
   * @return 
   * @throws parseexception 
   */ 
  public static int getdaysbetween(string startdate, string enddate) 
      throws parseexception { 
    int daygap = 0; 
    if (startdate != null && startdate.length() > 0 && enddate != null 
        && enddate.length() > 0) { 
      date end = formatstringtodate(enddate, date_format_ymd); 
      date start = formatstringtodate(startdate, date_format_ymd); 
      daygap = getdaysbetween(start, end); 
    } 
    return daygap; 
  } 
 
  private static int getdaysbetween(date startdate, date enddate) { 
    return (int) ((enddate.gettime() - startdate.gettime()) / one_day_mills); 
  } 
 
  /** 
   * 计算两个日期之间的天数差 
   * @param startdate 
   * @param enddate 
   * @return 
   */ 
  public static int getdaysgapofdates(date startdate, date enddate) { 
    int date = 0; 
    if (startdate != null && enddate != null) { 
      date = getdaysbetween(startdate, enddate); 
    } 
    return date; 
  } 
 
  /** 
   * 计算两个日期之间的年份差距 
   * 
   * @param firstdate 
   * @param seconddate 
   * @return 
   */ 
 
  public static int getyeargapofdates(date firstdate, date seconddate) { 
    if (firstdate == null || seconddate == null) { 
      return 0; 
    } 
    calendar helpcalendar = calendar.getinstance(); 
    helpcalendar.settime(firstdate); 
    int firstyear = helpcalendar.get(calendar.year); 
    helpcalendar.settime(seconddate); 
    int secondyear = helpcalendar.get(calendar.year); 
    return secondyear - firstyear; 
  } 
 
  /** 
   * 计算两个日期之间的月份差距 
   * 
   * @param firstdate 
   * @param seconddate 
   * @return 
   */ 
  public static int getmonthgapofdates(date firstdate, date seconddate) { 
    if (firstdate == null || seconddate == null) { 
      return 0; 
    } 
 
    return (int) ((seconddate.gettime() - firstdate.gettime()) 
        / one_day_mills / 30); 
 
  } 
 
  /** 
   * 计算是否包含当前日期 
   * 
   * @param datys 
   * @return 
   */ 
  public static boolean iscontaincurrent(list<string> dates) { 
    boolean flag = false; 
    simpledateformat fmt = new simpledateformat(date_format_ymd); 
    date date = new date(); 
    string datestr = fmt.format(date); 
    for (int i = 0; i < dates.size(); i++) { 
      if (datestr.equals(dates.get(i))) { 
        flag = true; 
      } 
    } 
    return flag; 
  } 
 
  /** 
   * 从date开始计算time天后的日期 
   * 
   * @param date 
   * @param time 
   * @return 
   * @throws parseexception 
   */ 
  public static string getcalculatedatetostring(string startdate, int time) 
      throws parseexception { 
    string resultdate = null; 
    if (startdate != null && startdate.length() > 0) { 
      date date = formatstringtodate(startdate, date_format_ymd); 
      calendar c = calendar.getinstance(); 
      c.settime(date); 
      c.set(calendar.day_of_year, time); 
      date = c.gettime(); 
      resultdate = formatdatetostring(date, date_format_ymd); 
    } 
    return resultdate; 
  } 
 
  /** 
   * 获取从某日期开始计算,指定的日期所在该年的第几周 
   * 
   * @param date 
   * @param admitdate 
   * @return 
   * @throws parseexception 
   *       @ 
   */ 
  public static int[] getyearandweeks(string date, string admitdate) 
      throws parseexception { 
    calendar c = calendar.getinstance(); 
    c.settime(formatstringtodate(admitdate, date_format_ymd)); 
    int time = c.get(calendar.day_of_week); 
    return getweekandyear(date, 0, time); 
  } 
 
  /** 
   * 获取指定日期refdate,前或后一周的所有日期 
   * 
   * @param refdate 
   *      参考日期 
   * @param weekoffset 
   *      -1:上周 0:本周 1:下周 
   * @param startdate 
   *      哪天算一周的第一天 
   * @return yyyy-mm-dd 格式的日期 
   * @throws parseexception 
   *       @ 
   */ 
  public static list<string> getweekdaysarounddate(string refdate, 
      int weekoffset, string startdate) throws parseexception { 
    // 以startdate为一周的第一天 
    calendar c = calendar.getinstance(); 
    c.settime(formatstringtodate(startdate, date_format_ymd)); 
    int firstdayofweek = c.get(calendar.day_of_week); 
    // 获取相应周 
    int[] weekandyear = getweekandyear(refdate, weekoffset, firstdayofweek); 
    // 获取相应周的所有日期 
    return getweekdays(weekandyear[1], weekandyear[0], firstdayofweek); 
  } 
 
  /** 
   * 根据时间点获取时间区间 
   * 
   * @param hours 
   * @return 
   */ 
  public static list<string[]> gettimepointsbyhour(int[] hours) { 
    list<string[]> hourpoints = new arraylist<string[]>(); 
    string sbstart = ":00:00"; 
    string sbend = ":59:59"; 
    for (int i = 0; i < hours.length; i++) { 
      string[] times = new string[2]; 
      times[0] = hours[i] + sbstart; 
      times[1] = (hours[(i + 1 + hours.length) % hours.length] - 1) 
          + sbend; 
      hourpoints.add(times); 
    } 
    return hourpoints; 
  } 
 
  /** 
   * 
   * 根据指定的日期,增加或者减少天数 
   * 
   * @param date 
   * @param amount 
   * @return 
   */ 
  public static date adddays(date date, int amount) { 
    return add(date, calendar.day_of_month, amount); 
  } 
 
  /** 
   * 根据指定的日期,类型,增加或减少数量 
   * 
   * @param date 
   * @param calendarfield 
   * @param amount 
   * @return 
   */ 
  public static date add(date date, int calendarfield, int amount) { 
    if (date == null) { 
      throw new illegalargumentexception("the date must not be null"); 
    } 
    calendar c = calendar.getinstance(); 
    c.settime(date); 
    c.add(calendarfield, amount); 
    return c.gettime(); 
  } 
 
  /** 
   * 获取当前日期的最大日期 时间2014-12-21 23:59:59 
   * @return 
   */ 
  public static date getcurdatewithmaxtime() { 
    calendar c = calendar.getinstance(); 
    c.set(calendar.hour_of_day, 23); 
    c.set(calendar.minute, 59); 
    c.set(calendar.second, 59); 
    return c.gettime(); 
  } 
 
  /** 
   * 获取当前日期的最小日期时间 2014-12-21 00:00:00 
   * @return 
   */ 
  public static date getcurdatewithmintime() { 
    calendar c = calendar.getinstance(); 
    c.set(calendar.hour_of_day, 0); 
    c.set(calendar.minute, 0); 
    c.set(calendar.second, 0); 
    c.set(calendar.millisecond, 0); 
    return c.gettime(); 
  } 
 
} 

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