Reputation: 1056
I am trying to convert String to Date to compare from current Date and it throws parse Exception
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.US);
try {
java.util.Date cookiedate = format.parse("Tue Apr 29 11:40:55 GMT+04:00 2014");
Calendar currentDate = Calendar.getInstance();
String dateNow = format.format(currentDate.getTime());
java.util.Date currDate = format.parse(dateNow);
if (currDate.getTime() > cookiedate.getTime()) {
return true;
}
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Upvotes: 2
Views: 5596
Reputation: 9700
At first, you should parse the string date to Date
object using EEE MMM dd HH:mm:ss Z yyyy
format then convert that Date
to yyyy-MM-dd HH:mm:ss
format as follows...
SimpleDateFormat format = new SimpleDateFormat("EEE MMM dd HH:mm:ss Z yyyy");
try {
Date cookiedate = format.parse("Tue Apr 29 11:40:55 GMT+04:00 2014");
Calendar currentDate = Calendar.getInstance();
format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.US);
cookiedate = format.parse(format.parse(cookiedate));
String dateNow = format.format(currentDate.getTime());
Date currDate = format.parse(dateNow);
if (currDate.getTime() > cookiedate.getTime()) {
return true;
}
} catch (ParseException e) {
e.printStackTrace();
}
Upvotes: 2
Reputation: 115328
I think it is pretty obvious that formatted date "Tue Apr 29 11:40:55 GMT+04:00 2014"
does not match format "yyyy-MM-dd HH:mm:ss"
.
If you are using format "yyyy-MM-dd HH:mm:ss"
you should parse strings like 2014-03-30 10"59:23
.
If you want to parse string like "Tue Apr 29 11:40:55 GMT+04:00 2014"
you should use format like EEE MMM dd HH:mm:ss z yyyy
. (I am not sure about z
, probably it should be Z
).
Upvotes: 1
Reputation: 1697
In your format
, "yyyy-MM-dd HH:mm:ss"
will match date string like "2013-03-30 15:57:00"
, so you get a ParseException
.
If you want to parse "Tue Apr 29 11:40:55 GMT+04:00 2014"
, you should use "EEE MMM dd HH:mm:ss z yyyy"
Change your code to
SimpleDateFormat format = new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy", Locale.US);
Upvotes: 3