我有日期,date1(now)和date2,它们以JSON字符串返回,说2016-07-09 21:26:04
。
我想比较这两个日期,如下所示
if(date1 < date2){
}
以下是在 Android 中比较两个 DateTime 对象的代码:
public void onDateSelected(DateTime dateSelected) {
DateTime currentDateTime = new DateTime();
try{
// You can use any format to compare by spliting the dateTime
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZZZZZ");
String str1 = dateSelected.toString();
Date selectedDate = formatter.parse(str1);
String str2 = currentDateTime.toString();
Date currentDate = formatter.parse(str2);
if (selectedDate.compareTo(currentDate)<0)
{
System.out.println("current date is Greater than my selected date");
}
else
{
System.out.println("selected date is Greater than my current date");
}
}catch (ParseException e1){
e1.printStackTrace();
}
}
我会这样做:
- 解析 in to Date 对象
- 比较那些
例:
public static void main(String x[]) throws ParseException {
String s1 = "2016-07-09 21:26:04";
String s2 = "2006-07-09 21:26:04";
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date d1 = sdf.parse(s1);
Date d2 = sdf.parse(s2);
int compareResult = d1.compareTo(d2);
if (compareResult > 0) {
System.out.println(s1 + " is younger than " + s2);
} else if (compareResult < 0) {
System.out.println(s1 + " is younger than " + s2);
} else {
System.out.println(s1 + " is equals than " + s2);
}
}
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
Date today= new Date();
try {
if (today.before(sdf.forrmat(json_string_date))) {
// If start date is before end date.
// Do your piece of code
}
}catch (ParseException e) {
e.printStackTrace();
}