• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

comparing two dates

 
Ranch Hand
Posts: 1282
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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
 
author & internet detective
Posts: 41860
908
Eclipse IDE VI Editor Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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()
 
miguel lisboa
Ranch Hand
Posts: 1282
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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
Posts: 1282
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
i sorted it out

[ December 19, 2004: Message edited by: miguel lisboa ]
 
Jeanne Boyarsky
author & internet detective
Posts: 41860
908
Eclipse IDE VI Editor Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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
Posts: 1282
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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 ]
 
Bartender
Posts: 1844
Eclipse IDE Ruby Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Just do the following:

 
miguel lisboa
Ranch Hand
Posts: 1282
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Joel:
but what you recommend is precisely what i had, before another poster recomended that i use DateFormat instead...
 
Jeanne Boyarsky
author & internet detective
Posts: 41860
908
Eclipse IDE VI Editor Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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
Posts: 1282
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

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 ]
 
Ranch Hand
Posts: 1646
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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 ]
 
Ranch Hand
Posts: 5093
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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.
 
David Harkness
Ranch Hand
Posts: 1646
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

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
Posts: 1282
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

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 ]
 
Ranch Hand
Posts: 517
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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.
 
miguel lisboa
Ranch Hand
Posts: 1282
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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
Posts: 1646
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

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
Posts: 1282
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

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
Posts: 1646
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

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
reply
    Bookmark Topic Watch Topic
  • New Topic