how to compare two dates in java in a simple way - java

I want to know if there is a simple way to compare two dates of this format for example :
Wed, 31 Jul 2013 09:31:51
Mon, 05 Aug 2013 10:18:24
and display the greatest date?

I'd suggest you to use Joda library. Using the date info you have, create DateTime instances and call isBefore() method to determine which one comes first.

I would check the documentation, which shows that Date implements Comparable<Date> and so
date1.compareTo(date2);
will do what you want. You may wish to ensure that date1 is not null.
If your dates are (in fact) Strings, then use SimpleDateFormat's parse() method to convert from strings to dates, and then perform that comparison.
As others have suggested, Joda is a better date/time library (better API and threading performance).

Date d1, d2;
This returns greatest dates:
d1.after(d2) ? d1 : d2;

first parse the string into a Date object using a SimpleDateFormat :
String dateStringA = "Wed, 31 Jul 2013 09:31:51";
String dateStringB = "Mon, 05 Aug 2013 10:18:24";
SimpleDateFormat parserSDF = new SimpleDateFormat("EEE, DD MMM yyyy HH:mm:ss");
Date dateA = parserSDF.parse(dateStringA);
Date dateB = parserSDF.parse(dateStringB);
if (dateA.compareTo(dateB) > 0) {
System.out.println("A bigger");
}
then compare the Date objects using compareTo method

You can use Date's getTime() method and then use < >.

This will work for you
DateFormat df=new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss");
Date date1=df.parse("Wed, 31 Jul 2013 09:31:51");
Date date2=df.parse("Mon, 05 Aug 2013 10:18:24");
System.out.println(date1.after(date2) ? date1 : date2);

Related

Missing Month and Day In Java SimpleDateFormat parse

Using SimpleDateFormat:
DateFormat df = new SimpleDateFormat("dd-MMMM-YYYY kk:mm:ss.SSS");
Date extractedDate = df.parse(possibleDate);
Input given:
11-May-2017 21:45:33.614
Output data object:
Sun Jan 01 21:45:33 MST 2017
I have tried lots of iterations but it won't pull the month and day.
Use dd-MMM-yyyy kk:mm:ss.SSS as pattern
Example :
DateFormat df = new SimpleDateFormat("dd-MMM-yyyy kk:mm:ss.SSS");
Date extractedDate = df.parse("11-May-2017 21:45:33.614");
System.out.println(extractedDate);
Output :
Thu May 11 21:45:33 BDT 2017
Another thing If you use kk for hour, hour should be represent between 1 to 24. If the hour between 0 to 23 use HH instead of kk

Can't convert string to date in Java, wrong timezone after conversion

I have an array of Strings with the dates e.g.:
Tue, 09 Feb 2016 14:07:00 GMT;
Tue, 09 Feb 2016 19:55:00 GMT.
Now I want to find the most recent date on this list. In order to do that, I try to deserialize these strings to java.util.Date objects and after that compare them.
The code sample of java.util.Date object generation:
strDate = "Tue, 09 Feb 2016 14:07:00 GMT";
DateFormat format = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z");
Date date;
try {
date = format.parse(strDate);
//Result: Tue Feb 09 16:07:00 IST 2016
System.out.println("Result: " + date.toString());
} catch(ParseException e) {
e.printStackTrace();
}
My questions:
Why is the result in IST 2016 time zone and not in GMT? What does the IST 2016 stand for? Is it India Standard Time or Irish Standard Time or Israel Standard Time?
The initial string is in EEE, dd MMM format, the SimpleDateFormat pattern is also in this format, thus, why the result is in EEE, MMM dd format?
How can get a java.util.Date object in the same timezone as the initial string, in my case — GMT?
Is the approach I'm using to find the most recent date in the list is OK or there is more convenient/modern way to do that in Java 8, e.g., with the usage of LocalDateTime?
You are relying to Date.toString() to print your date when you should format it to a String with a formatter. What you are seeing is just the default pattern of Date.toString(). What you must keep in mind is that a Date does not have a timezone. You are seeing the output with the IST timezone, this must be because the current locale for the JVM is set to some specific locale for which the timezone name is "IST".
With regard to your point 4, yes, you can do it much cleaner with Java Time API introduced in Java 8. You can create a List of your strings to parse, create a DateTimeFormatter to parse it, and keep the maximum date value.
public static void main(String[] args) {
List<String> dates = Arrays.asList("Tue, 09 Feb 2016 14:07:00 GMT", "Tue, 09 Feb 2016 19:55:00 GMT");
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("EEE, dd MMM yyyy HH:mm:ss z", Locale.ENGLISH);
ZonedDateTime maxDate = dates.stream()
.map(s -> ZonedDateTime.parse(s, formatter))
.max(ZonedDateTime::compareTo)
.get(); // or .orElse(null)
System.out.println(maxDate);
}
This code is using a ZonedDateTime to keep the time-zone of the incoming strings.
Your computer seems to be set to IST. To force GMT output, import java.util.TimeZone and do this in your try block:
format.setTimeZone(TimeZone.getTimeZone("GMT"));
date = format.parse(strDate);
System.out.println("Result: " + format.format(date));

SimpleDateFormat function parse(String s) gives wrong date

As an input I have Date object(for example, exDate=Fri Aug 01 00:00:00 EEST 2014) that must be formated. After the parsing of the date, I get wrong date.
SimpleDateFormat sdf = new SimpleDateFormat(
"dd-MMM-YYYY hh.mm.ss.SSSSSSSSS aa", Locale.ENGLISH);
String dateStart = sdf.format(exDate);
Date dateF = sdf.parse(dateStart);
dateStart will be equal to
01-Aug-2014 12.00.00.000000000 AM
and the resut, dateF will be equal to
Sun Dec 29 00:00:00 EET 2013
So, after the parsing of a string with date, the result is wrong.
Maybe, somebody know the source of the problem? Or another way to format date in another SimpleDateFormat?
The problem is the YYYY which means:
Y Week year;
The actual year, which is what you are looking for would be yyyy.
I really recommend that you go in the link above to see the full list.
You should also replace the milliseconds to .SSS as you can't get more precise than that.

Check between MM-dd-yyyy and dd-MM-yyyy formats in Java

I have some data which contains date in different formats, eg: yyyy-dd-MM, yyyy-MM-dd, EEE dd-MM-yy etc.
I am trying to find a way to differentiate between dd-MM-yyyy and MM-dd-yyyy.
I understand that if dd is less than 12, there is no way I can be sure about format, However by identifying other cases when dd > 12, I can minimize the the wrong calculation.
I tried this -
SimpleDateFormat targetFormat = new SimpleDateFormat("EEE, yyyy-MMM-dd hh:mm:ss a");
SimpleDateFormat originalFormat1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
SimpleDateFormat originalFormat2 = new SimpleDateFormat("yyyy-dd-MM HH:mm:ss");
Calendar cal = Calendar.getInstance();
try {
Date date = originalFormat1.parse(s); //I tried with s = "2013-25-8 20:10:00";
cal.setTime(date);
if (cal.get(Calendar.DAY_OF_MONTH) > 12)
date = originalFormat2.parse(s);
System.out.println(targetFormat.format(date));
} catch (ParseException e) {
System.out.println("Error");
Output
I was expecting : Sun, 2013-Aug-25 08:10:00 PM
But I got : Thu, 2015-Jan-08 08:10:00 PM
You can try:
originalFormat1.setLenient(false);
before you try to parse a string with it; that should make it throw a ParseException when the month number is out of range.
When you apply format 1 and it interprets 25 as month then the date starts to become weird, that makes sense as month cannot be bigger than 12. Therefore, your if statement doesn't make sense. You have to check the format before applying the SimpleDateFormat (for instance with Integer.parseInt(s.substring(5,7) > 12).
Hey actually it is taking 25 as month, So 12 + 12 + 1 means 2 years and one month i.e "January"
So, your date becomes : "Thu Jan 08 20:10:00 GMT 2015" and again when you are changing it into "targetFormat" , this unusual result ensues...

Java - unparseable date, need format to match "GMT-0400"

I have the following Java:
DateFormat formatter = new SimpleDateFormat(
"EEE MMM dd yyyy HH:mm:ss zZ (zzzz)", Locale.ENGLISH);
Calendar cal = Calendar.getInstance();
cal.set(2011, Calendar.APRIL, 1);
out.println(formatter.format(cal.getTime()));
out.println();
Date date;
try {
date = formatter
.parse("Fri Apr 01 2011 00:00:00 GMT-0400 (Eastern Daylight Time)");
} catch (ParseException e) {
out.println("Failed to parse date: " + e.getMessage());
e.printStackTrace(out);
}
This is in a servlet, and the Calendar-constructed date comes out as:
Fri Apr 01 2011 16:42:24 EDT-0400 (Eastern Daylight Time)
This looks like the same format as the date string I'm trying to parse, except for EDT-0400 versus the desired GMT-0400. The code fails when trying to parse the date string:
java.text.ParseException: Unparseable date: "Fri Apr 01 2011 00:00:00 GMT-0400 (Eastern Daylight Time)"
How can I parse such a string? This is coming from a JavaScript date in a Sencha Touch 1.1.1 model, stored in WebSQL local storage.
For some reason GMT-0400 isnt' working, and UTC-0400 is working. You can replace GMT with UTC.
Note that this part will be completely ignored - the timezone will be resolved from what's found in the brackets (at least on my machine, JDK 6)
I debugged SimpleDateFormat and it seems that it will only parse GMT-04:00 but not GMT-0400.
It will accept UTC-0400, however it will throw away the hours/minutes modifier and will incorrectly parse it as UTC. (This happens with any other timezone designation, except for GMT)
It will also parse -0400 correctly, so the most robust solution is probably to simply remove GMT from your date string.
The upshot of the story is that SimpleDateFormat is anything but simple.
Update: Another lesson is that I could've saved a lot of time by passing a ParsePosition object to the parse() method:
DateFormat formatter = new SimpleDateFormat(
"EEE MMM dd yyyy HH:mm:ss zzzz", Locale.ENGLISH);
Date date;
ParsePosition pos = new ParsePosition( 0 );
date = formatter
.parse("Fri Apr 01 2011 00:00:00 UTC-0400", pos);
System.out.println( pos.getIndex() );
Will print out 28, indicating that the parsing ended at character index 28, just after UTC.

Categories