首页 行业资讯 宠物日常 宠物养护 宠物健康 宠物故事

java中年月日怎样比较大小

发布网友 发布时间:2022-04-26 21:53

我来回答

4个回答

热心网友 时间:2023-11-07 13:47

用毫秒比较,虽然是伪毫秒,但是相当精确
String date1 = "2007-10-12 18:35:00";
String date2 = "2008-10-12 18:35:00";
String pattern ="yyyy-MM-dd hh:mm:ss";
SimpleDateFormat sf = new SimpleDateFormat(pattern);
Date d1 = sf.parse(date1);
Date d2 = sf.parse(date2);
if(d1.getTime() > d2.getTime()){
System.out.println("date 1 > date 2");
}else{
System.out.println("date 1 < date 2");
}

热心网友 时间:2023-11-07 13:48

如果是Date类型把他转化成String类型比较,直接用String里的方法
strA.compareTo(strB)就可以 >0 strA的时间在后,<0 相反, =0时候两个时间相等

热心网友 时间:2023-11-07 13:47

用毫秒比较,虽然是伪毫秒,但是相当精确
String date1 = "2007-10-12 18:35:00";
String date2 = "2008-10-12 18:35:00";
String pattern ="yyyy-MM-dd hh:mm:ss";
SimpleDateFormat sf = new SimpleDateFormat(pattern);
Date d1 = sf.parse(date1);
Date d2 = sf.parse(date2);
if(d1.getTime() > d2.getTime()){
System.out.println("date 1 > date 2");
}else{
System.out.println("date 1 < date 2");
}

热心网友 时间:2023-11-07 13:48

一楼走弯路了,Date类型就可直接比较的,
Date a=...
Date b=...
int i=a.compareTo(b);
if(i>0)...
else if(i<0)...
else ...

热心网友 时间:2023-11-07 13:49

/**
* Compares two Dates for ordering.
*
* @param anotherDate the <code>Date</code> to be compared.
* @return the value <code>0</code> if the argument Date is equal to
* this Date; a value less than <code>0</code> if this Date
* is before the Date argument; and a value greater than
* <code>0</code> if this Date is after the Date argument.
* @since 1.2
* @exception NullPointerException if <code>anotherDate</code> is null.
*/
public int compareTo(Date anotherDate) {
long thisTime = getMillisOf(this);
long anotherTime = getMillisOf(anotherDate);
return (thisTime<anotherTime ? -1 : (thisTime==anotherTime ? 0 : 1));
}

参考DATE源代码..

热心网友 时间:2023-11-07 13:48

如果是Date类型把他转化成String类型比较,直接用String里的方法
strA.compareTo(strB)就可以 >0 strA的时间在后,<0 相反, =0时候两个时间相等

热心网友 时间:2023-11-07 13:48

一楼走弯路了,Date类型就可直接比较的,
Date a=...
Date b=...
int i=a.compareTo(b);
if(i>0)...
else if(i<0)...
else ...

热心网友 时间:2023-11-07 13:49

/**
* Compares two Dates for ordering.
*
* @param anotherDate the <code>Date</code> to be compared.
* @return the value <code>0</code> if the argument Date is equal to
* this Date; a value less than <code>0</code> if this Date
* is before the Date argument; and a value greater than
* <code>0</code> if this Date is after the Date argument.
* @since 1.2
* @exception NullPointerException if <code>anotherDate</code> is null.
*/
public int compareTo(Date anotherDate) {
long thisTime = getMillisOf(this);
long anotherTime = getMillisOf(anotherDate);
return (thisTime<anotherTime ? -1 : (thisTime==anotherTime ? 0 : 1));
}

参考DATE源代码..

声明声明:本网页内容为用户发布,旨在传播知识,不代表本网认同其观点,若有侵权等问题请及时与本网联系,我们将在第一时间删除处理。E-MAIL:11247931@qq.com