java.util.Date 比较大小

方法一:

调用Date的getTime()方法获取到毫秒数来进行比较

String beginTime = "2018-07-28 14:42:32";
String endTime = "2018-07-29 12:26:32";
 
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
 
try {
	Date date1 = format.parse(beginTime);
	Date date2 = format.parse(endTime);
	
	long beginMillisecond = date1.getTime();
	long endMillisecond = date2.getTime();
	
	System.out.println(beginMillisecond > endMillisecond);
	
} catch (ParseException e) {
	e.printStackTrace();
}

方法二:

String beginTime = "2018-07-28 14:42:32";
String endTime = "2018-07-29 12:26:32";
 
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
 
try {
	Date date1 = format.parse(beginTime);
	Date date2 = format.parse(endTime);
	
	boolean before = date1.before(date2);
	
	System.out.println(before);
	
} catch (ParseException e) {
	e.printStackTrace();
}

before()或者after()方法的返回值为boolean类型

方法三:

String beginTime = "2018-07-28 14:42:32";
String endTime = "2018-07-29 12:26:32";
 
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
 
try {
	Date date1 = format.parse(beginTime);
	Date date2 = format.parse(endTime);
	
	int compareTo = date1.compareTo(date2);
	
	System.out.println(compareTo);
	
} catch (ParseException e) {
	e.printStackTrace();
}

compareTo()方法的返回值,date1小于date2返回-1,date1大于date2返回1,相等返回0

猜你喜欢

转载自blog.csdn.net/fanbaodan/article/details/86493422
今日推荐