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

Java日期操作方法工具类实例【包含日期比较大小,相加减,判断,验证,获取年份等】

程序员文章站 2024-02-13 13:08:34
本文实例讲述了java日期操作方法工具类。分享给大家供大家参考,具体如下: package com.gcloud.common; import org.apac...

本文实例讲述了java日期操作方法工具类。分享给大家供大家参考,具体如下:

package com.gcloud.common;
import org.apache.http.util.textutils;
import java.text.parseexception;
import java.text.simpledateformat;
import java.util.calendar;
import java.util.date;
import java.util.regex.pattern;
/**
 * 日期时间工具类
 * created by charlin on 2017/9/3.
 */
public class dateutil {
 public static final string china_date_format = "yyyy年mm月dd日";
 public static final string datetime_format = "yyyy-mm-dd hh:mm:ss";
 public static final string date_format = "yyyy-mm-dd";
 public static final string time_format = "hh:mm:ss";
 //----------------判断-----------------------------------------------
 /**
 * 是否是润年
 * @param yearnum
 * @return
 */
 public static boolean isleapyear(int yearnum) {
 boolean isleep = false;
 if ((yearnum % 4 == 0) && (yearnum % 100 != 0))
  isleep = true;
 else if (yearnum % 400 == 0)
  isleep = true;
 else {
  isleep = false;
 }
 return isleep;
 }
 /**
 * 判断是否是日期
 *
 * @param date
 * @return
 */
 public static boolean isdate(string date) {
 //判断年月日的正则表达式,接受输入格式为2010-12-24,可接受平年闰年的日期
 string regex = "(([0-9]{3}[1-9]|[0-9]{2}[1-9][0-9]{1}|[0-9]{1}[1-9][0-9]{2}|[1-9][0-9]{3})-(((0[13578]|1[02])-(0[1-9]|[12][0-9]|3[01]))|((0[469]|11)-(0[1-9]|[12][0-9]|30))|(02-(0[1-9]|[1][0-9]|2[0-8]))))|((([0-9]{2})(0[48]|[2468][048]|[13579][26])|((0[48]|[2468][048]|[3579][26])00))-02-29)";
 pattern pattern = pattern.compile(regex);
 return pattern.matcher(date).matches();
 }
 /**
 * 验证是不是生日
 *
 * @param birthday
 * @return
 */
 public static boolean verifybirthday(string birthday) {
 if (textutils.isempty(birthday)) return false;
 if (!birthday.contains("-")) return false;
 string[] arr = birthday.split("-");
 if (null == arr || arr.length != 3 || arr[0].length() != 4 || arr[1].length() != 2 || arr[2].length() != 2)
  return false;
 int year = getyear(new date());
 int birthyear = integer.parseint(arr[0]);
 if (birthyear <= 1900 || birthyear > year) return false;
 string curdate = formatdate(new date(), date_format);
 if (birthday.compareto(curdate) > 0) return false;
 return isdate(birthday);
 }
 //-------------------自动转化--------------------------------------------
 /**
 * 把字符串自动转化为时间格式
 *
 * @param datestr
 * @return
 */
 public static date parsedatebyauto(string datestr) {
 if (stringutil.isempty(datestr)) {
  return null;
 }
 string format = date_format;
 if (datestr.indexof("/") > -1) {
  format = format.replace("-", "/");
 }
 if (datestr.indexof(":") != -1) {
  format += " hh:mm";
 }
 //存在秒
 if (datestr.indexof(":") != datestr.lastindexof(":")) {
  format += ":ss";
 }
 return parsedate(datestr, format);
 }
 /**
 * 自动识别格式
 * @param date
 * @return
 */
 public static string formatdatebyauto(date date){
 string format = date_format;
 if( !(date instanceof java.sql.date) && (date.getseconds()>0||date.getminutes()>0||date.gethours()>0)){
  format = datetime_format;
 }
 return formatdate(date, format);
 }
 //------------当前日期与时间 --------------------------------
 /**取当前日期*/
 public static date getcurrdate() {return parsedate(formatdate(new date())); }
 /**取当前时间*/
 public static date getcurrdatetime() {return parsedate(formatdate(new date())); }
 /**取当前日期*/
 public static string getcurrdatestr() { return formatdate(new date()); }
 /**取当前时间*/
 public static string getcurrdatetimestr() { return formatdate(new date(), datetime_format);}
 public static string formatcurrdate() {return formatdate(new date(),date_format); }
 public static string formatcurrdatetime() {return formatdate(new date(),datetime_format);}
 public static string formatcurrdatetos(string strformat) {return formatdate(new date(), strformat); }
 //-----------时间计算--------------------------------------------
 /**
 * 时间相减
 * @param strdatebegin
 * @param strdateend
 * @param itype
 * @return
 */
 public static int getdiffdate(string strdatebegin, string strdateend, int itype) {
 calendar calbegin = calendar.getinstance();
 calbegin.settime(parsedate(strdatebegin, datetime_format));
 calendar calend = calendar.getinstance();
 calbegin.settime(parsedate(strdateend, datetime_format));
 long lbegin = calbegin.gettimeinmillis();
 long lend = calend.gettimeinmillis();
 if (itype == calendar.second)
  return (int) ((lend - lbegin) / 1000l);
 if (itype == calendar.minute)
  return (int) ((lend - lbegin) / 60000l);
 if (itype == calendar.hour)
  return (int) ((lend - lbegin) / 3600000l);
 if (itype == calendar.day_of_month) {
  return (int) ((lend - lbegin) / 86400000l);
 }
 return -1;
 }
 /**
 * 添加天数或月份或年得到新的时间
 *
 * @param strdate
 * @param count
 * @param daytype calendar.year
 * @return
 */
 public static string getadddatetime(string strdate, int count, int daytype) {
 calendar cal = calendar.getinstance();
 cal.settime(parsedate(strdate));
 cal.add(daytype, count);
 simpledateformat sdf = null;
 if ((daytype == calendar.year) || (daytype == calendar.month) || (daytype == calendar.day_of_month))
  sdf = new simpledateformat(date_format);
 else
  sdf = new simpledateformat(datetime_format);
 return sdf.format(cal.gettime());
 }
 /**
 * 日期增加天数
 * @param date
 * @param icount
 * @return
 */
 public static date getadddate(date date, int icount) {
 calendar cal = calendar.getinstance();
 cal.settime(date);
 cal.add(calendar.day_of_month, icount);
 return cal.gettime();
 }
 /**
 * 比较日期
 *
 * @param datestr1
 * @param datestr2
 * @return
 */
 public static int comparedate(string datestr1, string datestr2) {
 date date1 = parsedate(datestr1);
 date date2 = parsedate(datestr2);
 if (date1.gettime() > date2.gettime())
  return -1;
 else if (date1.gettime() < date2.gettime())
  return 1;
 else
  return 0;
 }
 public static int comparedate(date date1, date date2) {
 if (date1.gettime() > date2.gettime())
  return -1;
 else if (date1.gettime() < date2.gettime())
  return 1;
 else
  return 0;
 }
 /**
 * 时间差
 *
 * @param startdate
 * @param enddate
 * @return
 */
 public static int getdiffdays(date startdate, date enddate) {
 int days = 0;
 if (startdate.after(enddate)) {
  date temp = startdate;
  startdate = enddate;
  enddate = temp;
 }
 days = (int) (enddate.gettime() - startdate.gettime()) / 1000 * 60 * 60 * 24;
 return days;
 }
 /**
 * 当前日期的后几天
 *
 * @param date
 * @param n
 * @return
 */
 public static date getafterday(date date, int n) {
 calendar c = calendar.getinstance();
 c.settime(date);
 c.add(calendar.date, n);
 return c.gettime();
 }
 //---------获取时间天数----------------------------------------------
 /**
 * 获取当前月的最后一天
 *
 * @param datestr
 * @return
 */
 public static string getmonthend(string datestr) {
 //当前第一天
 date date = parsedate(getmonthbegin(datestr));
 calendar c = calendar.getinstance();
 c.settime(date);
 c.add(calendar.month, 1);
 c.add(calendar.day_of_year, -1);
 return formatdate(c.gettime());
 }
 public static string getmonthend(date date) {
 calendar c = calendar.getinstance();
 c.settime(date);
 c.set(calendar.date, c.getactualmaximum(calendar.date));
 return formatdate(c.gettime());
 }
 /**
 * 获得当前日期的月份第一天
 *
 * @param datestr
 * @return
 */
 public static string getmonthbegin(string datestr) {
 date date = parsedate(datestr);
 return formatdate(date, "yyyy-mm") + 01;
 }
 public static string getmonthbegin(date date) {
 return formatdate(date, "yyyy-mm") + 01;
 }
 //--------------格式化日期-----------------------------------------
 /**
 * 格式化日期为字符串
 *
 * @param date
 * @param format
 * @return
 */
 public static string formatdate(date date, string format) {
 return new simpledateformat(format).format(date);
 }
 public static string formatdate(date date) {
 return formatdate(date, date_format);
 }
 public static string formatechinadate(date date) {
 return formatdate(date, china_date_format);
 }
 public static string formatedatetime(date date) {
 return formatdate(date, datetime_format);
 }
 public static string formatetime(date date) {
 return formatdate(date, time_format);
 }
 //-----------------格式化字符串为日期--------------------------------------
 /**
 * 格式化字符串为日期
 *
 * @param date
 * @param format
 * @return
 */
 public static date parsedate(string date, string format) {
 try {
  return new simpledateformat(format).parse(date);
 } catch (parseexception e) {
  e.printstacktrace();
 }
 return null;
 }
 public static date parsedate(string date) { return parsedate(date, date_format);}
 public static date parsechinadate(string date) {
 return parsedate(date, china_date_format);
 }
 public static date parsedatetime(string date) {
 return parsedate(date, datetime_format);
 }
 public static date parsetime(string date) {
 return parsedate(date, time_format);
 }
 //---获取年月日时分秒----------------------------------------------------
 /**
 * 获取年份
 *
 * @param date
 * @return
 */
 public static int getyear(date date) {
 calendar c = calendar.getinstance();
 c.settime(date);
 return c.get(calendar.year);
 }
 /**
 * 获取月份
 *
 * @param date
 * @return
 */
 public static int getmonth(date date) {
 calendar c = calendar.getinstance();
 c.settime(date);
 return c.get(calendar.month) + 1;
 }
 /**
 * 获取日
 *
 * @param date
 * @return
 */
 public static int getday(date date) {
 calendar c = calendar.getinstance();
 c.settime(date);
 return c.get(calendar.day_of_month);
 }
 /**
 * 获取星期
 *
 * @param date
 * @return
 */
 public static int getweek(date date) {
 calendar c = calendar.getinstance();
 c.settime(date);
 return c.get(calendar.day_of_week);
 }
 /**
 * 获取时间
 *
 * @param date
 * @return
 */
 public static int gethour(date date) {
 calendar c = calendar.getinstance();
 c.settime(date);
 return c.get(calendar.hour_of_day);
 }
 /**
 * 获取分种
 *
 * @param date
 * @return
 */
 public static int getminute(date date) {
 calendar c = calendar.getinstance();
 c.settime(date);
 return c.get(calendar.minute);
 }
 /**
 * 获取秒
 *
 * @param date
 * @return
 */
 public static int getsecond(date date) {
 calendar c = calendar.getinstance();
 c.settime(date);
 return c.get(calendar.second);
 }
 //--------------获取星期几---------------------------------------------------
 /**
 * 获取星期几
 *
 * @param strdate
 * @return
 */
 public static string getweekdayname(string strdate) {
 string[] mname = {"日", "一", "二", "三", "四", "五", "六"};
 date date = parsedate(strdate);
 int week = getweek(date);
 return "星期" + mname[week];
 }
 public static string getweekdayname(date date) {
 string[] mname = {"日", "一", "二", "三", "四", "五", "六"};
 int week = getweek(date);
 return "星期" + mname[week];
 }
 /**
 * 一年中的星期几
 * @return
 */
 public static int getweeknumofyear(date date) {
 calendar calendar = calendar.getinstance();
 calendar.settime(date);
 return calendar.get(calendar.week_of_year);
 }
 public static int getweeknumofyear(string date) {
 calendar calendar = calendar.getinstance();
 calendar.settime(parsedate(date, date_format));
 return calendar.get(calendar.week_of_year);
 }
 /**
 * 获取本周星期一的日期
 * @param yearnum
 * @param weeknum
 * @return
 * @throws parseexception
 */
 public static string getyearweekfirstday(int yearnum, int weeknum) {
 calendar cal = calendar.getinstance();
 cal.set(calendar.year, yearnum);
 cal.set(calendar.week_of_year, weeknum);
 cal.set(calendar.day_of_week, 2);
 string tempyear = integer.tostring(yearnum);
 string tempmonth = integer.tostring(cal.get(calendar.month) + 1);
 string tempday = integer.tostring(cal.get(calendar.day_of_month)-1);
 return tempyear + "-" + tempmonth + "-" + tempday;
 }
 /**
 * 获取本周星期天的日期
 * @param yearnum
 * @param weeknum
 * @return
 * @throws parseexception
 */
 public static string getyearweekendday(int yearnum, int weeknum) {
 calendar cal = calendar.getinstance();
 cal.set(calendar.year, yearnum);
 cal.set(calendar.week_of_year, weeknum + 1);
 cal.set(calendar.day_of_week, 1);
 string tempyear = integer.tostring(yearnum);
 string tempmonth = integer.tostring(cal.get(calendar.month) + 1);
 string tempday = integer.tostring(cal.get(calendar.day_of_month)-1);
 return tempyear + "-" + tempmonth + "-" + tempday;
 }
 //--------------获取天数---------------------------------------------------
 /**
 * 获取某年某月的第一天
 * @param yearnum
 * @param monthnum
 * @return
 */
 public static date getyearmonthfirstday(int yearnum, int monthnum) {
 calendar cal = calendar.getinstance();
 cal.set(yearnum, monthnum - 1, 1, 0, 0, 0);
 cal.set(14, 0);
 return cal.gettime();
 }
 /**
 * 获取某年下个月的第一天
 * @param yearnum
 * @param monthnum
 * @return
 */
 public static date getnextyearmonthfirstday(int yearnum, int monthnum) {
 calendar cal = calendar.getinstance();
 cal.set(yearnum, monthnum, 1, 0, 0, 0);
 cal.set(14, 0);
 return cal.gettime();
 }
 /**
 * 获取某年某月的最后一天
 * @param yearnum
 * @param monthnum
 * @return
 */
 public static date getyearmonthendday(int yearnum, int monthnum) {
 calendar cal = calendar.getinstance();
 cal.set(yearnum, monthnum, 0, 0, 0, 0);
 cal.set(14, 0);
 return cal.gettime();
 }
 /**
 * 获取某月的第一天
 * @param date
 * @return
 */
 public static date getyearmonthfirstday(date date) {
 calendar cal = calendar.getinstance();
 cal.settime(date);
 cal.set(5, 1);
 cal.set(11, 0);
 cal.set(12, 0);
 cal.set(13, 0);
 cal.set(14, 0);
 return cal.gettime();
 }
 /**
 * 获取下一年的第一天
 * @param date
 * @return
 */
 public static date getnextyearmonthfirstday(date date) {
 calendar cal = calendar.getinstance();
 cal.settime(date);
 cal.add(2, 1);
 cal.set(5, 1);
 cal.set(11, 0);
 cal.set(12, 0);
 cal.set(13, 0);
 cal.set(14, 0);
 return cal.gettime();
 }
 /**
 * 获取当前月的最后一天
 * @param date
 * @return
 */
 public static date getyearmonthendday(date date) {
 calendar cal = calendar.getinstance();
 cal.settime(date);
 cal.set(5, cal.getactualmaximum(5));
 cal.set(11, 0);
 cal.set(12, 0);
 cal.set(13, 0);
 cal.set(14, 0);
 return cal.gettime();
 }
 /**
 * 获取当年的第一天
 * @param yearnum
 * @return
 */
 public static date getyearfirstday(int yearnum) {
 calendar cal = calendar.getinstance();
 cal.set(yearnum, 0, 1, 0, 0, 0);
 cal.set(14, 0);
 return cal.gettime();
 }
 /**
 * 获取下一年的第一天
 * @param yearnum
 * @return
 */
 public static date getnextyearfirstday(int yearnum) {
 calendar cal = calendar.getinstance();
 cal.set(yearnum, 12, 1, 0, 0, 0);
 cal.set(14, 0);
 return cal.gettime();
 }
 /**
 * 获取当年的最后一天
 * @param yearnum
 * @return
 */
 public static date getyearendday(int yearnum) {
 calendar cal = calendar.getinstance();
 cal.set(yearnum, 12, 0, 0, 0, 0);
 cal.set(14, 0);
 return cal.gettime();
 }
 /**
 * 获取当前星期
 * @param strdate
 * @param weeknum
 * @return
 */
 public static string getweek(string strdate, int weeknum) {
 calendar c = calendar.getinstance();
 c.settime(parsedate(strdate));
 if (weeknum == 1)
  c.set(7, 2);
 else if (weeknum == 2)
  c.set(7, 3);
 else if (weeknum == 3)
  c.set(7, 4);
 else if (weeknum == 4)
  c.set(7, 5);
 else if (weeknum == 5)
  c.set(7, 6);
 else if (weeknum == 6)
  c.set(7, 7);
 else if (weeknum == 0)
  c.set(7, 1);
 return formatdate(c.gettime());
 }
 public static date getweek(date date, int weeknum) {
 calendar c = calendar.getinstance();
 c.settime(date);
 if (weeknum == 1)
  c.set(7, 2);
 else if (weeknum == 2)
  c.set(7, 3);
 else if (weeknum == 3)
  c.set(7, 4);
 else if (weeknum == 4)
  c.set(7, 5);
 else if (weeknum == 5)
  c.set(7, 6);
 else if (weeknum == 6)
  c.set(7, 7);
 else if (weeknum == 0)
  c.set(7, 1);
 return c.gettime();
 }
 /**
 * 下个月日期
 * @param date
 * @return
 */
 public static date getnextmonday(date date) {
 calendar c = calendar.getinstance();
 c.settime(date);
 do
  c.add(calendar.day_of_month, 1);
 while (c.get(calendar.day_of_week) != 2);
 return c.gettime();
 }
 /**
 * 获得某一日期的前一天
 *
 */
 public static date getpreviousdate(date date) {
 calendar calendar = calendar.getinstance();
 calendar.settime(date);
 calendar.add(calendar.date, -1);
 calendar.set(calendar.hour, 0);
 calendar.set(calendar.second, 0);
 calendar.set(calendar.minute, 0);
 calendar.set(calendar.millisecond, 0);
 return getsqldate(calendar.gettime());
 }
 /**
 * 获得某年某月最后一天的日期
 *
 */
 public static date getlastdayofmonth(int year, int month) {
 calendar calendar = calendar.getinstance();
 calendar.set(calendar.year, year);
 calendar.set(calendar.month, month);
 calendar.set(calendar.date, 1);
 return getpreviousdate(getsqldate(calendar.gettime()));
 }
 /**
 * 获取一个月的天数
 * @param year
 * @param month
 * @return
 */
 public static int getdaysinmonth(int year, int month) {
 calendar cal = calendar.getinstance();
 cal.set(calendar.year, year);
 cal.set(calendar.month, month - 1);// java月份才0开始算
 return cal.getactualmaximum(calendar.date);
 }
 //----------------根据用户生日计算年龄-------------------------------------------------
 /**
 * 根据用户生日计算年龄
 */
 public static int getagebybirthday(date birthday) {
 calendar cal = calendar.getinstance();
 if (cal.before(birthday)) {
  throw new illegalargumentexception("the birthday is before now.it's unbelievable!");
 }
 int yearnow = cal.get(calendar.year);
 int monthnow = cal.get(calendar.month) + 1;
 int dayofmonthnow = cal.get(calendar.day_of_month);
 cal.settime(birthday);
 int yearbirth = cal.get(calendar.year);
 int monthbirth = cal.get(calendar.month) + 1;
 int dayofmonthbirth = cal.get(calendar.day_of_month);
 int age = yearnow - yearbirth;
 if (monthnow <= monthbirth) {
  if (monthnow == monthbirth) {
  if (dayofmonthnow < dayofmonthbirth) {
   age--;
  }
  } else {
  age--;
  }
 }
 return age;
 }
 /**
 * 由java.util.date到java.sql.date的类型转换
 *
 */
 public static date getsqldate(java.util.date date) {
 return new date(date.gettime());
 }
 public static void main(string[] args) {
 //dd
 system.out.println("测试结果:");
 system.out.println("2017年 2月最后一天日期为:"+getlastdayofmonth(2017, 2));
 system.out.println("2017年第一天日期为:"+getyearfirstday(2017));
 system.out.println("2017年最后一天日期为:"+getyearendday(2017)); }
}

运行结果:

Java日期操作方法工具类实例【包含日期比较大小,相加减,判断,验证,获取年份等】

ps:这里再为大家推荐几款关于日期与时间计算的在线工具供大家参考使用:

在线日期/天数计算器:

在线万年历日历:

在线阴历/阳历转换工具:

unix时间戳(timestamp)转换工具:

附:本例中用到了org.apache.http.util.textutils包,相关的jar包文件可点击此处。

eclipse导入jar包的实现方法可参考本站

更多关于java相关内容感兴趣的读者可查看本站专题:《java日期与时间操作技巧汇总》、《java数据结构与算法教程》、《java操作dom节点技巧总结》和《java缓存操作技巧汇总

希望本文所述对大家java程序设计有所帮助。