[英]Compare two dates with time whose Formate is yyyy-MM-dd HH:mm:ss in Android
I have to compare two dates whose format is yyyy-MM-dd HH:mm:ss . 我必须比较格式为yyyy-MM-dd HH:mm:ss的两个日期。 I know the way to compare date only the before or after date function. 我知道比较日期只能在日期之前或日期之后的方法。
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String currentDateandTime = sdf.format(new Date());
String expiryTime = "2014-09-10 00:00:00";
But what's the best way to compare date and time with the current date and time. 但是,将日期和时间与当前日期和时间进行比较的最佳方法是什么。 Like we have two dates 2014-09-10 00:00:00 and current date with time is 2014-08-31 10:37:15. 就像我们有两个日期2014-09-10 00:00:00和当前日期的时间是2014-08-31 10:37:15。 And now we have to compare it. 现在我们要比较它。 How we can do that. 我们怎么做到这一点。
Any help is appreciated. 任何帮助表示赞赏。
Convert the Date String to java.util.Date
object using SimpleDateFormat and compare those date objects with Date#after
or Date#before
methods. 使用SimpleDateFormat将Date String转换为java.util.Date
对象,并将这些日期对象与Date#after
或Date#before
方法进行比较。
In java 8 - using new Java Time API , parse date String using DateTimeFormat
and get LocalDate
object and compare them. 在java 8中 - 使用新的Java Time API ,使用DateTimeFormat
解析日期String并获取LocalDate
对象并进行比较。
DateTimeFormatter dtf = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss");
final LocalDate dt1 = dtf.parseLocalDate(dateString1);
final LocalDate dt2 = dtf.parseLocalDate(dateString2);
final boolean check = dt1.isAfter(dt2);
if(check)
System.out.println(dt1 +" is after "+dt2);
else
System.out.println(dt2 +" is after "+dt1);
If I understand what you're trying to do you want to use a SimpleDateFormat
(and you posted a good pattern) to parse the String
(s) into Date
(s) and then Date.before(Date)
. 如果我理解你想要做什么,你想使用SimpleDateFormat
(你发布了一个好的模式)来将String
解析为Date
(s),然后Date.before(Date)
。 Putting that together into something like, 将它们组合成类似的东西,
DateFormat sdf = new SimpleDateFormat(
"yyyy-MM-dd HH:mm:ss");
String firstStr = "2014-09-10 00:00:00";
String secondStr = "2014-08-31 10:37:15";
Date first = sdf.parse(firstStr);
Date second = sdf.parse(secondStr);
boolean before = (first.before(second));
System.out.printf("%s is before %s",
before ? firstStr : secondStr,
before ? secondStr : firstStr);
Output is 输出是
2014-08-31 10:37:15 is before 2014-09-10 00:00:00
try{
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
} catch (ParseException e1)
{
// TODO Auto-generated catch block
e1.printStackTrace();
}
String str1 = "2014-09-10 00:00:00";
Date date1 = formatter.parse(str1);
String str2 = "2014-08-31 10:37:15";
Date date2 = formatter.parse(str2);
if (date1.compareTo(date2)<0)
{
System.out.println("date2 is Greater than my date1");
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.