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

Java对日期Date类进行加减运算、年份加减月份加减、时间差等等

程序员文章站 2024-03-09 14:53:59
实现代码一: import java.text.simpledateformat; import java.util.calendar; import jav...

实现代码一:

import java.text.simpledateformat;
import java.util.calendar;
import java.util.date;

public class datetestutil { 
 public static void main(string[] args) throws exception {  
  simpledateformat sdf=new simpledateformat("yyyymmdd");
  string str="20110823";
  date dt=sdf.parse(str);
  calendar rightnow = calendar.getinstance();
  rightnow.settime(dt);
  rightnow.add(calendar.year,-1);//日期减1年
  rightnow.add(calendar.month,3);//日期加3个月
  rightnow.add(calendar.day_of_year,10);//日期加10天
  date dt1=rightnow.gettime();
  string restr = sdf.format(dt1);
  system.out.println(restr);
 }
}

注:在calendar对象的add方法中,第二个参数为正数表示“加”,负数表示“减”。

代码二: java date 日期加减天数

测试类代码:

import java.text.simpledateformat; 
import java.util.date; 
 
public class datetest { 
   
  public static void main(string[] arg){ 
    date now = new date();    
     
    addandsubtractdaysbygettime(now,-5); 
    addandsubtractdaysbygettime(now,5); 
    addandsubtractdaysbycalendar(now,-5); 
    addandsubtractdaysbycalendar(now,5); 
  } 
   
   public static date addandsubtractdaysbygettime(date datetime/*待处理的日期*/,int n/*加减天数*/){ 
      
     //日期格式 
     simpledateformat df=new simpledateformat("yyyy-mm-dd");  
     simpledateformat dd=new simpledateformat("yyyy-mm-dd hh:mm:ss");     
      
     system.out.println(df.format(new date(datetime.gettime() + n * 24 * 60 * 60 * 1000l))); 
     //system.out.println(dd.format(new date(datetime.gettime() + n * 24 * 60 * 60 * 1000l))); 
     //注意这里一定要转换成long类型,要不n超过25时会出现范围溢出,从而得不到想要的日期值 
     return new date(datetime.gettime() + n * 24 * 60 * 60 * 1000l); 
   } 
    
   public static date addandsubtractdaysbycalendar(date datetime/*待处理的日期*/,int n/*加减天数*/){ 
      
     //日期格式 
     simpledateformat df=new simpledateformat("yyyy-mm-dd");  
     simpledateformat dd=new simpledateformat("yyyy-mm-dd hh:mm:ss");  
      
     java.util.calendar calstart = java.util.calendar.getinstance(); 
       calstart.settime(datetime); 
 
     calstart.add(java.util.calendar.day_of_week, n);  
      
     system.out.println(df.format(calstart.gettime())); 
     //system.out.println(dd.format(calstart.gettime())); 
     return calstart.gettime(); 
   } 
 
}

运行结果:
2014-10-06
2014-10-16
2014-10-06
2014-10-16

代码三:

在网上查阅资料,加上自己总结的一些关于date类的工具类。

package com.data.utils;

import java.text.simpledateformat;
import java.util.calendar;
import java.util.date;

public class dateformat {

 /**
  * 日期减几年
  */
 public static string dateminusyear(string str) throws exception {

  simpledateformat sdf = new simpledateformat("yyyymm");
  date dt = sdf.parse(str);
  calendar rightnow = calendar.getinstance();
  rightnow.settime(dt);
  rightnow.add(calendar.year, -1);// 日期减1年
  date dt1 = rightnow.gettime();
  string restr = sdf.format(dt1);
  return restr;
 }

 /**
  * 日期加几年
  */
 public static string dateaddyear(string str) throws exception {

  simpledateformat sdf = new simpledateformat("yyyymm");
  date dt = sdf.parse(str);
  calendar rightnow = calendar.getinstance();
  rightnow.settime(dt);
  rightnow.add(calendar.year, 1);// 日期加1年
  date dt1 = rightnow.gettime();
  string restr = sdf.format(dt1);
  return restr;
 }

 /**
  * 日期减几月
  */
 public static string dateminusmonth(string str) throws exception {

  simpledateformat sdf = new simpledateformat("yyyymm");
  date dt = sdf.parse(str);//将字符串生成date
  calendar rightnow = calendar.getinstance();
  rightnow.settime(dt);//使用给定的 date 设置此 calendar 的时间。 
  rightnow.add(calendar.month, -1);// 日期减1个月
  date dt1 = rightnow.gettime();//返回一个表示此 calendar 时间值的 date 对象。
  string restr = sdf.format(dt1);//将给定的 date 格式化为日期/时间字符串,并将结果添加到给定的 stringbuffer。
  return restr;
 }

 /**
  * 日期加几月
  */
 public static string dateaddmonth(string str) throws exception {

  simpledateformat sdf = new simpledateformat("yyyymm");
  date dt = sdf.parse(str);
  calendar rightnow = calendar.getinstance();
  rightnow.settime(dt);
  rightnow.add(calendar.month, 1);// 日期加3个月
  // rightnow.add(calendar.day_of_year,10);//日期加10天
  date dt1 = rightnow.gettime();
  string restr = sdf.format(dt1);
  return restr;
 }

 /**
  * 获取当前年月的第一个月的str
  * @param str
  *   201505
  * @return 201501
  * @throws exception
  */
 public static string dateonemonth(string str) {

  str = str.substring(0, str.length() - 2);
  str = str + "01";
  return str;
 }

 /**
  * 算出所选月份距离一月份有几个月。
  * @param str 201509
  * @return 9
  */
 public static int datedistancemonth(string str) {

  int i = integer.parseint(str);
  int j = integer.parseint(dateformat.dateonemonth(str));
  system.out.println(i - j);
  return i - j + 1;
 }

 /**
  * 获取两个时间的时间差,精确到毫秒
  * @param str
  * @return
  */
 public static string timedifference(long start, long end) {

  long between = end - start;
  long day = between / (24 * 60 * 60 * 1000);
  long hour = (between / (60 * 60 * 1000) - day * 24);
  long min = ((between / (60 * 1000)) - day * 24 * 60 - hour * 60);
  long s = (between / 1000 - day * 24 * 60 * 60 - hour * 60 * 60 - min * 60);
  long ms = (between - day * 24 * 60 * 60 * 1000 - hour * 60 * 60 * 1000
    - min * 60 * 1000 - s * 1000);
  string timedifference = day + "天" + hour + "小时" + min + "分" + s + "秒" + ms
    + "毫秒";
  return timedifference;
 }
}

 /**
  * 获取24小时、一周、一个月的起始时间
  * 
  * @param timeinterval
  *   : day_time_interval week_time_interval month_time_interval
  * @return "yyyy-mm-dd hh:mm:ss"
  */
 public static string getstarttime(int timeinterval) {
  calendar cal = calendar.getinstance();
  simpledateformat sdf = new simpledateformat("yyyy-mm-dd hh:mm:ss");
  if (day_time_interval == timeinterval) {// 获取24小时的起始时间
   cal.set(calendar.hour_of_day, 0);
   cal.set(calendar.minute, 0);
   cal.set(calendar.second, 0);
   string starttime = sdf.format(cal.gettime());
   return starttime;
  } else if (week_time_interval == timeinterval) {
   int weekday = cal.get(calendar.day_of_week) - 1;
   cal.add(calendar.date, -weekday);
   cal.set(calendar.hour_of_day, 0);
   cal.set(calendar.minute, 0);
   cal.set(calendar.second, 0);
   string starttime = sdf.format(cal.gettime());
   return starttime;
  } else if (month_time_interval == timeinterval) {
   int dayofmonthmin = cal.getactualminimum(calendar.day_of_month);
   // c.add(calendar.date, -dayofmonth);
   cal.set(calendar.date, dayofmonthmin);
   cal.set(calendar.hour_of_day, 0);
   cal.set(calendar.minute, 0);
   cal.set(calendar.second, 0);
   string starttime = sdf.format(cal.gettime());
   return starttime;
  }
  return null;
 }

 /**
  * 获取24小时、一周、一个月的结束时间
  * 
  * @param timeinterval
  *   : day_time_interval week_time_interval month_time_interval
  * @return "yyyy-mm-dd hh:mm:ss"
  */
 public static string getendtime(int timeinterval) {
  calendar cal = calendar.getinstance();
  cal.settimezone(timezone.gettimezone("gmt+8"));
  simpledateformat sdf = new simpledateformat("yyyy-mm-dd hh:mm:ss");
  if (day_time_interval == timeinterval) {
   cal.set(calendar.hour_of_day, 23);
   cal.set(12, 59);
   cal.set(13, 59);
   long date = cal.gettimeinmillis();
   string endtime = sdf.format(new date(date));
   return endtime;
  } else if (week_time_interval == timeinterval) {
   int weekday = cal.get(calendar.day_of_week) - 1;
   cal.add(calendar.date, -weekday);
   cal.add(calendar.date, 6);
   cal.set(calendar.hour_of_day, 23);
   cal.set(12, 59);
   cal.set(13, 59);
   long date = cal.gettimeinmillis();
   string endtime = sdf.format(new date(date));
   return endtime;
  } else if (month_time_interval == timeinterval) {
   int dayofmonthmax = cal.getactualmaximum(calendar.day_of_month);
   cal.set(calendar.date, dayofmonthmax);
   cal.set(calendar.hour_of_day, 23);
   cal.set(calendar.minute, 59);
   cal.set(calendar.second, 59);
   string endtime = sdf.format(cal.gettime());
   return endtime;
  }
  return null;
 }
 /**
  * 判断datestr是否在start和end中间,start和end都可以为null yyyymmddhhmmss或者yyyymmdd格式
  * 
  * @author you.xu
  * @date 2015年8月19日下午3:11:46
  * @param datestr
  * @param start
  * @param end
  * @return
  */
 public static boolean checkdateval(string datestr, string start, string end) {
  boolean isdateright = false;
  date date = null;
  date startdate = null;
  date enddate = null;
  simpledateformat sdf = null;
  // 判断日期格式
  if (14 == datestr.length()) {
   sdf = new simpledateformat("yyyymmddhhmmss");
  } else if (8 == datestr.length()) {
   sdf = new simpledateformat("yyyymmdd");
  } else
   return false;

  try {
   // 更改判断日期格式
   date = sdf.parse(datestr);
  } catch (parseexception e) {
   log.error(e, e);
  }

  if ((start == null) && (end != null)) {
   try {
    enddate = sdf.parse(end);
   } catch (parseexception ex1) {
    log.error(ex1, ex1);
   }
   if ((date != null) && (enddate != null))// check parameters for
   {
    if (date.compareto(enddate) <= 0)
     isdateright = true;
   }
  } else if ((start != null) && (end == null)) {
   try {
    startdate = sdf.parse(start);
   } catch (parseexception ex1) {
    log.error(ex1, ex1);
   }
   if ((date != null) && (startdate != null)) {
    if (date.compareto(startdate) >= 0)
     isdateright = true;
   }
  } else if ((start != null) && (end != null)) {
   try {
    startdate = sdf.parse(start);
    enddate = sdf.parse(end);
   } catch (parseexception ex2) {
    system.out.println(ex2.tostring());
   }
   if ((startdate != null) && (date != null) && (enddate != null)) {
    if ((date.compareto(startdate) >= 0)
      && (date.compareto(enddate) <= 0))
     isdateright = true;
   }
  }
  return isdateright;
 }

 /**
  * 判断datestr是否在start和end中间,start和end都可以为null long形格式
  * 
  * @author you.xu
  * @date 2015年8月19日下午3:12:35
  * @param datestr
  * @param start
  * @param end
  * @return
  */
 public static boolean checkdatev(string datestr, string start, string end) {
  boolean isdateright = false;
  long date = -1;
  long fromdate = -1;
  long todate = -1;

  date = java.lang.long.parselong(datestr);

  if ((start == null) && (end == null)) {
   isdateright = true;
  } else if ((start == null) && (end != null)) {
   try {
    todate = java.lang.long.parselong(end);
   } catch (numberformatexception nfe) {
    log.error(nfe, nfe);
   }
   if (date <= todate) {
    isdateright = true;
   }
  } else if ((start != null) && (end == null)) {
   try {
    fromdate = java.lang.long.parselong(start);
   } catch (numberformatexception nfe) {
    log.error(nfe, nfe);
   }

   if (date >= fromdate) {
    isdateright = true;
   }
  } else if ((start != null) && (end != null)) {
   try {
    todate = java.lang.long.parselong(end);
    fromdate = java.lang.long.parselong(start);
   } catch (numberformatexception nfe) {
    log.error(nfe, nfe);
   }

   if ((date <= todate) && (date >= fromdate)) {
    isdateright = true;
   }
  }
  return isdateright;
 }

目前就用到了这些,随时添加,有简单方便的时间工具类,希望和大家一起学习,在评论中指出。thanks!!!