关于date日期类型的大小比较
1.通过date提供的compareto()进行比较
java.util.date类实现了comparable接口
可以直接调用date的compareto()方法来比较大小
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
2.通过date自带的before()或者after()方法比较
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类型。
3.通过调用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(); }
总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持代码网。
发表评论