Welcome to the MacNN Forums.

If this is your first visit, be sure to check out the FAQ by clicking the link above. You may have to register before you can post: click the register link above to proceed. To start viewing messages, select the forum that you want to visit from the selection below.

You are here: MacNN Forums > Software - Troubleshooting and Discussion > Developer Center > Java: Comparing two dates and displaying the diference

Java: Comparing two dates and displaying the diference
Thread Tools
depolitic
Registered User
Join Date: Feb 2003
Status: Offline
Reply With Quote
Apr 19, 2004, 11:03 AM
 
I want to take to dates and compare them and then print out the difference. The Thing is that I am unsure the best way to do this. Simple and easy.

This is some of the things I have been working on:

// Get a Calendar for current locale and time zone
java.util.Calendar cal = java.util.Calendar.getInstance();

// Figure out what day of the year today is
cal.setTime(new java.util.Date()); // Set to the current time
int dayOfYear = cal.get(java.util.Calendar.DAY_OF_YEAR); // What day of the year is it?
System.out.println("Day of the year " + dayOfYear);

// What day of the week does the leap day in the year 2000 occur on?
cal.set(2000, java.util.Calendar.FEBRUARY, 29); // Set year, month, day fields
int dayOfWeek = cal.get(java.util.Calendar.DAY_OF_WEEK); // Query a different field
System.out.println("Day of the Week " + dayOfWeek);

// What day of the month is the 3rd Thursday of May, 2001?
cal.set(java.util.Calendar.YEAR, 2001); // Set the year
cal.set(java.util.Calendar.MONTH, java.util.Calendar.MAY); // Set the month
cal.set(java.util.Calendar.DAY_OF_WEEK, java.util.Calendar.THURSDAY); // Set the day of week
cal.set(java.util.Calendar.DAY_OF_WEEK_IN_MONTH, 3); // Set the week
int dayOfMonth = cal.get(java.util.Calendar.DAY_OF_MONTH); // Query the day in month
System.out.println( "Day of the Month " + dayOfMonth);

// Get a Date object that represents 30 days from now
java.util.Date today = new java.util.Date(java.util.Calendar.DAY_OF_MONTH); // Current date
java.util.Date startDate = new java.util.Date(java.util.Calendar.DAY_OF_MONTH); // Current date

cal.setTime(today); // Set it in the Calendar object
cal.add(java.util.Calendar.DAY_OF_MONTH, 24); // Add 30 days
java.util.Date endDate = cal.getTime(); // Retrieve the resulting date


System.out.println("Today Date: " + startDate);
System.out.println("End Date: " + endDate);

How do I do --- countDown = endDate - startDate;

Or am I better of getting time in milli seconds and comparing and then converting into human readable time.
     
Arkham_c
Mac Elite
Join Date: Dec 2001
Location: Atlanta, GA, USA
Status: Offline
Reply With Quote
Apr 19, 2004, 01:37 PM
 
Originally posted by depolitic:

How do I do --- countDown = endDate - startDate;

Or am I better of getting time in milli seconds and comparing and then converting into human readable time.
Do you want the difference in days? This is probably the best way then:

Code:
// Get today as calendar cal.setTime(new java.util.Date()); // get time as milliseconds long now = cal.getTimeInMillis(); // Add 30 days cal.add(java.util.Calendar.DAY_OF_MONTH, 24); // get future time as milliseconds long future = cal.getTimeInMillis(); // calculate difference in days int days_difference = (future - now)/(1000*60*60*24); System.out.println("Difference: " + days_difference);
Mac Pro 2x 2.66 GHz Dual core, Apple TV 160GB, two Windows XP PCs
     
qyn
Dedicated MacNNer
Join Date: Dec 2000
Location: sj ca
Status: Offline
Reply With Quote
Apr 19, 2004, 01:50 PM
 
You should use the Cocoa NSDate class. This has a method for comparing dates (among other things). You can also use the NSGregorianDate (a subclass of NSDate) for more fine-grained control.

http://developer.apple.com/documenta...es/NSDate.html
http://developer.apple.com/documenta...endarDate.html
     
Turias
Mac Elite
Join Date: Nov 2003
Location: Minnesota
Status: Offline
Reply With Quote
Apr 19, 2004, 01:54 PM
 
Originally posted by qyn:
You should use the Cocoa NSDate class. This has a method for comparing dates (among other things). You can also use the NSGregorianDate (a subclass of NSDate) for more fine-grained control.

http://developer.apple.com/documenta...es/NSDate.html
http://developer.apple.com/documenta...endarDate.html
Last time I checked, the NSDate class wasn't available when programming in Java.
     
qyn
Dedicated MacNNer
Join Date: Dec 2000
Location: sj ca
Status: Offline
Reply With Quote
Apr 19, 2004, 03:17 PM
 
Originally posted by Turias:
Last time I checked, the NSDate class wasn't available when programming in Java.
Well, it's true that I'm not a Java programmer, but the link in my post points to Apple's developer docs for "Foundation Reference for Java". That implies it's available, no?
     
Turias
Mac Elite
Join Date: Nov 2003
Location: Minnesota
Status: Offline
Reply With Quote
Apr 19, 2004, 03:25 PM
 
Originally posted by qyn:
Well, it's true that I'm not a Java programmer, but the link in my post points to Apple's developer docs for "Foundation Reference for Java". That implies it's available, no?
That's correct... IF you want to mix Cocoa and Java into one application. Doing so, however, makes it so the resulting program can only be run on OS X, which kind of defeats one of the biggest selling points of Java. Plus, your application is not really Java anymore. It's a strange hybrid of Java and Cocoa.
     
depolitic  (op)
Registered User
Join Date: Feb 2003
Status: Offline
Reply With Quote
Apr 19, 2004, 06:32 PM
 
Thank you, I had something similar but I never did the division. (1000*60*60*24) - The question why are we dividing by 86400000. Why?

Also you need to cast from long to int so:

// calculate difference in days == 86400000
int daysDifference = (int) ((future - now)/(1000*60*60*24));

SO it works.
     
Arkham_c
Mac Elite
Join Date: Dec 2001
Location: Atlanta, GA, USA
Status: Offline
Reply With Quote
Apr 19, 2004, 07:51 PM
 
Originally posted by depolitic:
Thank you, I had something similar but I never did the division. (1000*60*60*24) - The question why are we dividing by 86400000. Why?

Also you need to cast from long to int so:

// calculate difference in days == 86400000
int daysDifference = (int) ((future - now)/(1000*60*60*24));

SO it works.
1000 milliseconds in a second
60 seconds in a minute
60 minutes in an hour
24 hours in a day

Code:
1000 msec 60 sec 60 min 24 hours --------- x ------ x ------ x ------ 1 sec 1 min 1 hour 1 day
So cross canceling units, you use this number to convert milliseconds to days.
Mac Pro 2x 2.66 GHz Dual core, Apple TV 160GB, two Windows XP PCs
     
absmiths
Mac Elite
Join Date: Sep 2000
Location: Edmond, OK USA
Status: Offline
Reply With Quote
Apr 19, 2004, 10:08 PM
 
I never mess with Calendars or Dates to calculate date differences - except to get the millisecond value for a specific time. I just present a time in days (just divide by days as shown already), or weeks (all weeks are seven days), and if really needed I show months in 4 week increments (not that precise, but never really comes up) or years in 52 week increments.

If you really wanted to be fancy, you could create a calendar that referred to January 1, 2000 00:00:00.000 and add your millisecond difference to that, then use the month day etc. fields to display the number of each unit.
     
Kristoff
Mac Elite
Join Date: Sep 2000
Location: in front of the keyboard
Status: Offline
Reply With Quote
Apr 20, 2004, 12:47 AM
 
Why do that when the Date object already refers to it as the number of milliseconds past a well defined point in time: January 1, 1970 00:00:00.000 GMT aka the epoch.

That being said...always use Date objects or your code will make no sense to people who may come after you. Then, when you want to display it in a format that makes sense, just use the SimpleDateFormat class.

No need to invent your own method of keeping track of time, and no need to do any math except for the single operation to get the difference between two millisecond values.

I have seen some pretty crazy code over the years that people have concocted odd ball date tracking classes and methods, and it always amazes me that it's almost as if they never bothered to read the API docs.
signatures are a waste of bandwidth
especially ones with political tripe in them.
     
depolitic  (op)
Registered User
Join Date: Feb 2003
Status: Offline
Reply With Quote
Apr 20, 2004, 09:43 PM
 
Continuing on what is the best way to test if the day has changed, I looked over java.util.time. Is thies the best way or should I do some kind of scheduling approach, to test at certain times or intervals? Or is their a third way.
     
Arkham_c
Mac Elite
Join Date: Dec 2001
Location: Atlanta, GA, USA
Status: Offline
Reply With Quote
Apr 20, 2004, 09:59 PM
 
Originally posted by depolitic:
Continuing on what is the best way to test if the day has changed, I looked over java.util.time. Is thies the best way or should I do some kind of scheduling approach, to test at certain times or intervals? Or is their a third way.
AFAIK there is no java.util.time -- there is a java.util.Timer but I doubt that's what you are looking for.

Look at java.util.GregorianCalendar for a nice date/time manipulation class.
Mac Pro 2x 2.66 GHz Dual core, Apple TV 160GB, two Windows XP PCs
     
depolitic  (op)
Registered User
Join Date: Feb 2003
Status: Offline
Reply With Quote
Apr 21, 2004, 02:54 AM
 
I had a look at java.util.Timer looks about right I think executes task at set times. Or is this overkill, is there a simpler way to test if the day has changed then to use java.util.Timer to look at midnight for the date. Or is this just better with java.util.GregorianCalendar and at midnight to run the:

int days_difference = (future - now)/(1000*60*60*24);

style code again.
     
absmiths
Mac Elite
Join Date: Sep 2000
Location: Edmond, OK USA
Status: Offline
Reply With Quote
Apr 21, 2004, 02:29 PM
 
Originally posted by Kristoff:
Why do that when the Date object already refers to it as the number of milliseconds past a well defined point in time: January 1, 1970 00:00:00.000 GMT aka the epoch.

That being said...always use Date objects or your code will make no sense to people who may come after you. Then, when you want to display it in a format that makes sense, just use the SimpleDateFormat class.

No need to invent your own method of keeping track of time, and no need to do any math except for the single operation to get the difference between two millisecond values.

I have seen some pretty crazy code over the years that people have concocted odd ball date tracking classes and methods, and it always amazes me that it's almost as if they never bothered to read the API docs.
Because Date objects are defined to represent a specific instant in time, not a time interval, as is being discussed here. I would never represent a time interval in actual months (in other words, January, February, etc, and all the variances including leap year, etc) because that can only be confusing. That is why I always resist reporting time intervals in months - I just use Years - Weeks - Days - Hours - Minutes - Seconds - Milliseconds. A length of time is NOT a date.

Besides, if a developer can't comprehend that dividing a millisecond time value by (1000(s) * 60(m) * 60(h) * 24(d)) gives the interval in days, then he needs to go back to school.

Date/Calendar/DateFormat are serious overkill for a lot of uses - including this one.
     
absmiths
Mac Elite
Join Date: Sep 2000
Location: Edmond, OK USA
Status: Offline
Reply With Quote
Apr 21, 2004, 02:33 PM
 
Originally posted by depolitic:
I had a look at java.util.Timer looks about right I think executes task at set times. Or is this overkill, is there a simpler way to test if the day has changed then to use java.util.Timer to look at midnight for the date. Or is this just better with java.util.GregorianCalendar and at midnight to run the:

int days_difference = (future - now)/(1000*60*60*24);

style code again.
I am confused now about what you need to do. The question of task execution didn't come up until just now.
     
Kristoff
Mac Elite
Join Date: Sep 2000
Location: in front of the keyboard
Status: Offline
Reply With Quote
Apr 21, 2004, 03:22 PM
 
Originally posted by absmiths:
Because Date objects are defined to represent a specific instant in time, not a time interval, as is being discussed here. blah blah blah. A length of time is NOT a date.
Look at the first post again:
Originally posted by depolitic:
I want to take to dates and compare them and then print out the difference. The Thing is that I am unsure the best way to do this. Simple and easy.
Looks like he wants to take two dates and compare them. I don't see him talking about intervals.


Originally posted by absmiths:
Besides, if a developer can't comprehend that dividing a millisecond time value by (1000(s) * 60(m) * 60(h) * 24(d)) gives the interval in days, then he needs to go back to school.
And perhaps you hit the nail on the head right there...

Originally posted by depolitic:
The question why are we dividing by 86400000. Why?
Having just come from fixing someone else's code where dates were represented as everything from longs (not that bad) to some sore of odd textual representation (terrible) when they all could have been Date objects.....it just makes me want to scream out loud RTFM!
signatures are a waste of bandwidth
especially ones with political tripe in them.
     
depolitic  (op)
Registered User
Join Date: Feb 2003
Status: Offline
Reply With Quote
Apr 21, 2004, 08:25 PM
 
I would never dare call myself a developer. A hobbyist, more then anything else. So do not assume that a random series of numbers will mean anything to anyone, beyond you.

(1000*60*60*24) <-- There is nothing that says here this is a 1 day in milliseconds.

As for going back to school I am at school, doing my second degree in Psychology. So no I may not know (1000*60*60*24) == a day, but does not make me worthy of your putdown.

then he needs to go back to school.
     
absmiths
Mac Elite
Join Date: Sep 2000
Location: Edmond, OK USA
Status: Offline
Reply With Quote
Apr 21, 2004, 09:22 PM
 
Originally posted by depolitic:
I would never dare call myself a developer. A hobbyist, more then anything else. So do not assume that a random series of numbers will mean anything to anyone, beyond you.

(1000*60*60*24) <-- There is nothing that says here this is a 1 day in milliseconds.

As for going back to school I am at school, doing my second degree in Psychology. So no I may not know (1000*60*60*24) == a day, but does not make me worthy of your putdown.
That was not meant as a comment for you, I was referring to Kristoff. Sorry for the confusion. When you are working with dates and times in Java (or computer languages in general) millisecond time values become second nature.
     
absmiths
Mac Elite
Join Date: Sep 2000
Location: Edmond, OK USA
Status: Offline
Reply With Quote
Apr 21, 2004, 09:36 PM
 
Originally posted by Kristoff:
Look at the first post again:


Looks like he wants to take two dates and compare them. I don't see him talking about intervals.
Perhaps you need to reread the exerpt you quoted. He said he wants to compare two dates and print out the difference. Unless you think the difference between 00:00:00 January 1, 2000 and 00:00:00 January 2, 2000 is 00:00:00 January 2, 1970, then we are talking about an interval - in this case one day.


And perhaps you hit the nail on the head right there...
Not sure what you are getting at here. This could simply enough disambiguate the code:

Code:
public final class DateConstants { public static final long ONE_SECOND = 1000; public static final long ONE_MINUTE = ONE_SECOND * 60; public static final long ONE_HOUR = ONE_MINUTE * 60; public static final long ONE_DAY = ONE_HOUR * 24; public static final long ONE_WEEK = ONE_DAY * 7; public static final long ONE_YEAR = ONE_WEEK * 52; }
Then code like:
Code:
// how many days in the time interval? long days = interval / ONE_DAY;
becomes rather pedestrian.


Having just come from fixing someone else's code where dates were represented as everything from longs (not that bad) to some sore of odd textual representation (terrible) when they all could have been Date objects.....it just makes me want to scream out loud RTFM!
If I advocated storing instances in time as "kk009-qwe" then you would have just cause to be annoyed. However, manipulating time in long data types is very old and straightforward. Besides, date objects are not ideal in all cases. Sending time samples over the network, for example, is certainly best handled by longs. Also, if I display an ignorance of the API then you can sing 5 choruses of RTFM to everyones great admiration. However, having used the Calendar (and Date, before that) API quite a bit, I find them as I said overly complicated for something this simple (determining the number of milliseconds elapsed between two instances in time). The Calendar API doesn't have to be used to the exclusion of everything else, and it certainly has it's place. If his original question had been "How do I add a number of units of time to a date and determine the resulting date" then the Calendar would be a perfect fit.
( Last edited by absmiths; Apr 21, 2004 at 09:49 PM. )
     
Kristoff
Mac Elite
Join Date: Sep 2000
Location: in front of the keyboard
Status: Offline
Reply With Quote
Apr 22, 2004, 03:17 AM
 
You're missing my point...so obviously I have failed to communicate.
The RTFM was a generalization because it seems nobody bothers to read the API anymore.
This whole thread just struck a nerve with me due to a bad personal experience concerning dates, time-stamps, and someone else's poorly written code.
And I understand the math, it was depolitic who did not.
Sigh....
signatures are a waste of bandwidth
especially ones with political tripe in them.
     
absmiths
Mac Elite
Join Date: Sep 2000
Location: Edmond, OK USA
Status: Offline
Reply With Quote
Apr 22, 2004, 10:19 AM
 
Originally posted by Kristoff:
You're missing my point...so obviously I have failed to communicate.
The RTFM was a generalization because it seems nobody bothers to read the API anymore.
This whole thread just struck a nerve with me due to a bad personal experience concerning dates, time-stamps, and someone else's poorly written code.
And I understand the math, it was depolitic who did not.
Sigh....
Maybe we can put this one to rest then. I am also aware that you understand these issues since I have read quite a few of your posts in this forum. I was actually responding to your post (about potential developers who won't understand date math) rather than suggesting that you yourself go back to school.

Hopefully this thread was at least useful to the original poster.
     
beamso
Fresh-Faced Recruit
Join Date: Nov 2001
Location: Melboune, Australia
Status: Offline
Reply With Quote
Apr 23, 2004, 03:30 AM
 
I realise this is probably late, but the Calendar.add() method can accept negative numbers, which is essentially subtraction.

So, you can use Calendar.before() or Calendar.after() to work out which date is larger, then subtract the smaller from it by going through the various fields (Calendar.YEAR, Calendar.MONTH_OF_YEAR, etc.) and working with the final result.
     
   
 
Forum Links
Forum Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts
BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Top
Privacy Policy
All times are GMT -4. The time now is 09:00 AM.
All contents of these forums © 1995-2017 MacNN. All rights reserved.
Branding + Design: www.gesamtbild.com
vBulletin v.3.8.8 © 2000-2017, Jelsoft Enterprises Ltd.,