事先荐读
《String、java.util.Date、java.sql.Date的互相转化总结》
核心算法利用了Date对象的compareTo()方法,源码如下:
public int compareTo(Date anotherDate) {
long thisTime = getMillisOf(this);
long anotherTime = getMillisOf(anotherDate);
return thisTime 0 ? date1 : date2;
} catch (ParseException e) {
e.printStackTrace();
}
return null;
}
完整代码
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class FindMaxTime {
private static Date getNewerTime(String time1, String time2, SimpleDateFormat sdf) {
try {
Date date1 = sdf.parse(time1);
Date date2 = sdf.parse(time2);
return date1.compareTo(date2)>0 ? date1 : date2;
} catch (ParseException e) {
e.printStackTrace();
}
return null;
}
public static void main(String[] args) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
System.out.println("更新的时间是:" + sdf.format(getNewerTime("2019-3-4", "2019-4-23", sdf)));
System.out.println("更新的时间是:" + sdf.format(getNewerTime("2019-5-1", "2018-1-14", sdf)));
}
}
测试结果:
更新的时间是:2019-04-23
更新的时间是:2019-05-01