【发布时间】:2016-10-10 14:02:09
【问题描述】:
我有日期、date1(now) 和 date2,它们以 JSON 字符串形式返回,例如 2016-07-09 21:26:04。
我想比较这两个日期
if(date1 < date2){
}
【问题讨论】:
标签: java android json datetime compare
我有日期、date1(now) 和 date2,它们以 JSON 字符串形式返回,例如 2016-07-09 21:26:04。
我想比较这两个日期
if(date1 < date2){
}
【问题讨论】:
标签: java android json datetime compare
这是在 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();
}
}
【讨论】:
我会这样做:
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();
}
【讨论】: