概述
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
public class TimeUtil {
public static void main(String[] args) {
TimeUtil result = new TimeUtil ();
System.out.println("相差日期为:" + result.daysSubtraction("2015-01-20", "2015-02-20"));
System.out.println("相差月份为:" + result.monthSubtraction("2015-01", "2016-06"));
System.out.println("相差年份为:" + result.yearSubtraction("2015", "2019"));
}
public static int daysSubtraction(String dateStr1, String dateStr2) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd");
try {
dateStr1 = sdf.format(sdf2.parse(dateStr1));
dateStr2 = sdf.format(sdf2.parse(dateStr2));
} catch (ParseException e) {
e.printStackTrace();
}
int year1 = Integer.parseInt(dateStr1.substring(0, 4));
int month1 = Integer.parseInt(dateStr1.substring(4, 6));
int day1 = Integer.parseInt(dateStr1.substring(6, 8));
int year2 = Integer.parseInt(dateStr2.substring(0, 4));
int month2 = Integer.parseInt(dateStr2.substring(4, 6));
int day2 = Integer.parseInt(dateStr2.substring(6, 8));
Calendar c1 = Calendar.getInstance();
c1.set(Calendar.YEAR, year1);
c1.set(Calendar.MONTH, month1 - 1);
c1.set(Calendar.DAY_OF_MONTH, day1);
Calendar c2 = Calendar.getInstance();
c2.set(Calendar.YEAR, year2);
c2.set(Calendar.MONTH, month2 - 1);
c2.set(Calendar.DAY_OF_MONTH, day2);
long mills =
c1.getTimeInMillis() - c2.getTimeInMillis();//2678400000
int ss = (int)(mills/1000);//秒
int mm = (int)(ss/60);//分钟
int hh = (int)(mm/60);//小时
int dd = (int)(hh/24);//天
return Math.abs((int) (mills / 1000 / 3600 / 24));
}
public static int monthSubtraction(String date1,String date2) {
SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM");
try {
Date d1 = sf.parse(date1);
Date d2 = sf.parse(date2);
Calendar cal1=Calendar.getInstance();
cal1.setTime(d1);
Calendar cal2=Calendar.getInstance();
cal2.setTime(d2);
return (Math.abs(cal2.get(1)-cal1.get(1)))*12+Math.abs((cal2.get(2)-cal1.get(2)));
} catch (ParseException e) {
e.printStackTrace();
}
return 0;
}
public static int yearSubtraction(String date1,String date2) {
SimpleDateFormat sf = new SimpleDateFormat("yyyy");
try {
Date d1 = sf.parse(date1);
Date d2 = sf.parse(date2);
Calendar cal1=Calendar.getInstance();
cal1.setTime(d1);
Calendar cal2=Calendar.getInstance();
cal2.setTime(d2);
return (cal2.get(1)-cal1.get(1));
} catch (ParseException e) {
e.printStackTrace();
}
return 0;
}
}
最后
以上就是会撒娇彩虹为你收集整理的java 时间运算 日期运算 日期加减 日期工具类的全部内容,希望文章能够帮你解决java 时间运算 日期运算 日期加减 日期工具类所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复