wood burning stoves 2.0*
The moose likes Java in General and the fly likes comparing two dates Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "comparing two dates" Watch "comparing two dates" New topic
Author

comparing two dates

miguel lisboa
Ranch Hand

Joined: Feb 08, 2004
Posts: 1281
if i make:
Date d1 = new Date();
Date d2 = new Date();
how can i compare them?
and another Q:
if i've stored in MySql (as a datetime type) a date like:
2004-12-18 19:18:46
how can i compare it with d1 or d2?
thanks in advance


java amateur
Jeanne Boyarsky
internet detective
Marshal

Joined: May 26, 2003
Posts: 30068
    
149

Miguel,

returns an int representing the comparision. It is zero if the two dates are equal (to the millisecond), a negative integer if d1 is earlier or a postive integer if d2 is earlier.

Using JDBC you can get the datetime field as a date:

Then you can compare it to d1 or d2 using compareTo()


[Blog] [JavaRanch FAQ] [How To Ask Questions The Smart Way] [Book Promos]
Blogging on Certs: SCEA Part 1, Part 2 & 3, Core Spring 3, OCAJP, OCPJP beta, TOGAF part 1 and part 2
miguel lisboa
Ranch Hand

Joined: Feb 08, 2004
Posts: 1281
in first place thanks for your help!

i'm doing a "home" app and now i understand that "date" will be input manually, not using new Date().

so i guess i can turn this around like this:

1. offer the user 3 fields: year, month, day.

2. then i translate them, (when necessary), and create a Calendar like:

Calendar um = new GregorianCalendar(2004, Calendar.DECEMBER, 17);

3. later on, i retrieve from database those 3 fields and build another Calendar:

Calendar dois = new GregorianCalendar(2004, Calendar.DECEMBER, 1);

4. Finally i'll use:

um.after(dois)

in order to compare the dates.

Does this way sounds too complicated? Do i have any alternative?
thanks once again

BTW: i'll be using hibernate
[ December 18, 2004: Message edited by: miguel lisboa ]
miguel lisboa
Ranch Hand

Joined: Feb 08, 2004
Posts: 1281
i sorted it out

[ December 19, 2004: Message edited by: miguel lisboa ]
Jeanne Boyarsky
internet detective
Marshal

Joined: May 26, 2003
Posts: 30068
    
149

Miguel,
That is a good approach. Note that DateFormat (the superclass of SimpleDateFormat) has a parse method that only takes one parameter. So you don't need the ParsePosition object.
miguel lisboa
Ranch Hand

Joined: Feb 08, 2004
Posts: 1281
thanks for your feedback!

i feel i'm in trouble with Class DateFormat DateFormat
as this one doesnt have a construct where i can pass the my format, i'm puzzled

see what happened:

now test junit test:

error msg:

java.text.ParseException: Unparseable date: "19/11/2004"
at java.text.DateFormat.parse(DateFormat.java:335)
at utilitarios.Datas.entraStringSaiDate(Datas.java:23)
at utilitarios.DatasTeste.testSaiDate(DatasTeste.java:47)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:585)
at junit.framework.TestCase.runTest(TestCase.java:154)
at junit.framework.TestCase.runBare(TestCase.java:127)
at junit.framework.TestResult$1.protect(TestResult.java:106)
at junit.framework.TestResult.runProtected(TestResult.java:124)
at junit.framework.TestResult.run(TestResult.java:109)
at junit.framework.TestCase.run(TestCase.java:118)
at junit.framework.TestSuite.runTest(TestSuite.java:208)
at junit.framework.TestSuite.run(TestSuite.java:203)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:421)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:305)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:186)

what am i doing wrong?
thanks in advance
[ December 20, 2004: Message edited by: miguel lisboa ]
Joel McNary
Bartender

Joined: Aug 20, 2001
Posts: 1817

Just do the following:



Piscis Babelis est parvus, flavus, et hiridicus, et est probabiliter insolitissima raritas in toto mundo.
miguel lisboa
Ranch Hand

Joined: Feb 08, 2004
Posts: 1281
Joel:
but what you recommend is precisely what i had, before another poster recomended that i use DateFormat instead...
Jeanne Boyarsky
internet detective
Marshal

Joined: May 26, 2003
Posts: 30068
    
149

Miguel,
I was actually recommending a very small change:

Since DateFormat is a superclass of SimpleDateFormat, you can call its parse method. That parse method is simpler because it only takes one argument.

Nice JUnit test!
miguel lisboa
Ranch Hand

Joined: Feb 08, 2004
Posts: 1281

i didnt realize the diference
yes, you'r absolutely right
in your opinion, should i throw or declare the exception?
thanks a lot
hmm i guess its a catch...

i learn by fun and by myself (with books and web) but i feel fine using tests: i just refactored, added a try/catch, run the test suite and feel secure: nothing broke - junit told me
[ December 20, 2004: Message edited by: miguel lisboa ]
David Harkness
Ranch Hand

Joined: Aug 07, 2003
Posts: 1646
I find JUnit (really Test-Driven Development) deeply satisfying as well. I've spent the past six weeks converting an EJB application to Hibernate and Spring, and at the same time I wrote as many unit tests as I could. Wow, did this pay off in spades -- especially while building the core framework which changed slightly with each newly implemented chunk of code.

Anyway, the reason you were getting the exception is that DateFormat chose a default format based on your default locale which put the month before the day of the month. While using your own date format is definitely the easiest route, there shuold be a way to set your locale to one that uses day of month first if you care to dig a little deeper. Take a look at the java.util.Locale class.

[Okay, posted without even putting in the part I was actually posting to write.]

I'm only passingly familiar with MySQL, but in Oracle the DATE type actually includes a time portion as well. However, I found that if I specified a Hibernate type of "date" instead of "timestamp," Hibernate strips the time portion before sending a java.util.Date to the database.
[ December 20, 2004: Message edited by: David Harkness ]
Jeroen Wenting
Ranch Hand

Joined: Oct 12, 2000
Posts: 5093
What I've done is provide a simple validation function that will return true or false depending on whether 2 dates entered are oldest first or latest first.
Mind it also returns false if there's a parse exception unless the exception occurrs on the first date and a flag is set explicitly allowing this.



ddf is a static DateFormat constructed using the default formatting string for our application.
validateDate() validates whether a single date can be parsed using the given formatting string.


42
David Harkness
Ranch Hand

Joined: Aug 07, 2003
Posts: 1646
Originally posted by Jeroen Wenting:
ddf is a static DateFormat constructed using the default formatting string for our application.
Just make sure you aren't using that code from multiple threads. DateFormat and its subclasses are not threadsafe.
miguel lisboa
Ranch Hand

Joined: Feb 08, 2004
Posts: 1281

and:

Doing it this way actually does the job: no hh,mm,ss

thanks everybody for helping


[ December 21, 2004: Message edited by: miguel lisboa ]
MInu
Ranch Hand

Joined: Oct 09, 2003
Posts: 517
SimpleDateFormat sdfInput = new SimpleDateFormat( "yyyy/MM/dd" );

SimpleDateFormat sdfOutput = new SimpleDateFormat ( "yyyy/MM/dd" );

String textDate1 = "first date";

String textDate2 = "second date";
D
Date date = sdfInput.parse( textDate1 );

Date date1 = sdfInput.parse( textDate2 );

int i=textDate1.compareTo(textDate2);

You can compare dates based on i's value.


God Gave Me Nothing I Wanted<br />He Gave Me Everything I Needed<br /> - Swami Vivekananda
miguel lisboa
Ranch Hand

Joined: Feb 08, 2004
Posts: 1281
David:
Anyway, the reason you were getting the exception is that DateFormat chose a default format based on your default locale which put the month before the day of the month. While using your own date format is definitely the easiest route, there shuold be a way to set your locale to one that uses day of month first if you care to dig a little deeper. Take a look at the java.util.Locale class.

i tried:

without success, since parseException keeps asking for try/catch ou declaration...
David Harkness
Ranch Hand

Joined: Aug 07, 2003
Posts: 1646
Originally posted by miguel lisboa:
Locale l = new Locale("pt, pt");
That should beHowever, looking at the JavaDocs for Locale I only see NumberFormat mentioned -- not DateFormat.

Regardless, if you fix the cause of the ParseException, you still have to catch or declare it in your throws clause. The catch/throw declaration is enforced by the compiler since ParseException is a checked exception.
miguel lisboa
Ranch Hand

Joined: Feb 08, 2004
Posts: 1281
Regardless, if you fix the cause of the ParseException, you still have to catch or declare it in your throws clause. The catch/throw declaration is enforced by the compiler since ParseException is a checked exception.

as, in order to avoid one line of code

i've to write much more, i guess i should stay with my original aproach. What do you say?
[ December 21, 2004: Message edited by: miguel lisboa ]
David Harkness
Ranch Hand

Joined: Aug 07, 2003
Posts: 1646
Originally posted by miguel lisboa:
in order to avoid one line of code
i've to write much more, i guess i should stay with my original aproach. What do you say?
I say go (re)read the JavaDocs for SimpleDateFormat.parse(String, ParsePosition). If it fails to parse, the position isn't updated, its error index is set, and null is returned. Thus you're deciding betweenandI vastly prefer using try-catch to handle error flows as the code in the try-block can proceed without regard to checking for errors. Having if-tests throughout your code checking for error conditions breaks up the flow, making it harder to read.

Regardless, you have to handle errors somehow, even if you consciously choose to ignore them (swallow in an empty catch-block or propagate to caller). I find it easier and clearer to do this with exceptions than return codes.

YMMV
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: comparing two dates
 
Similar Threads
Date Calculations - Difference between 2 dates is off
Question on Pass By Reference
Comparing dates.....Help.....Please
What is the output and Why
comparing date