今天工作中要用到两个Date时间对比,百度搜起来零零散散,所以在这整理一个汇总的,大家可以按标题下滑找到自己需要的:
一、日期转换
二、日期加一天
三、两个日期相互比较
一、日期转换 上代码
1. 字符串转换为日期
public Date parseDate(String strDate,String pattern){
if(strDate==null || pattern==null || "".equals(strDate.trim()) ||"".equals(pattern.trim()) ){
throw new IllegalArgumentException("字符串或日期格式为空");
}
Date date = null;
try{
SimpleDateFormat parser = new SimpleDateFormat(pattern);
date=parser.parse(strDate);
}catch (ParseException e) {
System.out.println("格式化失败" + e.getMessage());
}
return date;
}
2. 日期格式化为字符串
public String format(Date date, String pattern) {
if(date==null){
return "";
}
if (date == null || pattern == null || "".equals(pattern.trim())){
throw new IllegalArgumentException("日期或字符串格式为空");
}
String str = null;
try {
SimpleDateFormat parser = new SimpleDateFormat(pattern);
str = parser.format(date);
} catch (Exception e) {
System.out.println("不能转换" + e.getMessage());
}
return str;
}
3. 把一种格式的日期字符串格式化成另一种格式的日期字符串
public String format (String str, String oldP, String newP) {
if (str == null || "".equals(str.trim()) || oldP == null
|| "".equals(oldP.trim()) || newP == null
|| "".equals(newP.trim())){
throw new IllegalArgumentException("不能为空");
}
return format(parseDate(str,oldP),newP);
}
二、日期加天数(按自己需要的天数调整数字即可)
/*日期加+1天*/
public static Date dateAddOne(Date date) {
Calendar calendar = new GregorianCalendar();
calendar.setTime(date);
calendar.add(calendar.DATE,1); //把日期往后增加一天,整数 往后推,负数往前移动
date=calendar.getTime(); //这个时间就是日期往后推一天的结果
return date;
}
三、两个日期相互比较
public static void main(String[] args) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//创建两个时间(对照的就是你需要接收的时间参数)
Date date1 = new Date();
Date date2 = new Date();
//输出为yyyy-MM-dd HH:mm:ss
String s1 = sdf.format(date1);
String s2 = sdf.format(date2);
try {
//将两个时间转换为Date用作比较
Date startDate = sdf.parse(s1);
Date endDate = sdf.parse(s2);
//比较两个时间
int i = startDate.compareTo(endDate);
} catch (ParseException e) {
e.printStackTrace();
}
}
下面附一个 compareTo()封装方法的代码,感兴趣底层逻辑的小伙伴可以在工具中点进方法查看
public int compareTo(Date anotherDate) {
long thisTime = getMillisOf(this);
long anotherTime = getMillisOf(anotherDate);
return (thisTime<anotherTime ? -1 : (thisTime==anotherTime ? 0 : 1));
}
比较绕的应该是这一句:int i = (thisTime<anotherTime ? -1 :(thisTime==notherTime?0 :1));
这里使用了if-else的简洁写法。这样在一些繁琐的逻辑处理中还是挺好的,可以省却定义一些不必要的变量。代码也简洁多了,易读性提高了不少。如果你看多了这种写法,自然就会喜欢上了。
好了,这就是今天工作中碰到的操作时间,欢迎私信我一起畅游代码的海洋中。
————————————————
版权声明:本文为CSDN博主「曹·布斯」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/weixin_43863142/article/details/125067926