Page 1 of 2 12 LastLast
Results 1 to 20 of 24
  1. #1
    rustix is offline Member
    Join Date
    Jul 2008
    Location
    Sri Lanka
    Posts
    2
    Rep Power
    0

    Default [Very Urgent] Need help calculating difference between two dates

    I'm trying to write a code to display the current day and time, then accept two dates from the user and display the difference between the two dates. To display the current date and time, I've used the SimpleDateFormatter library but I'm having difficulty calculating the difference between two dates. Could someone please help me with this?

    Below is my code so far

    Java Code:
    import java.util.Date;
    import java.util.Scanner;
    import java.text.SimpleDateFormat;
    
    public class DateFormatter {
    	public void displayNow()
    	{
    		Date todaysDate = new Date();
    		SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MMM-dd HH:mm:ss");
    
    		String formattedDate = formatter.format(todaysDate);
    		System.out.println("Today's date and time is: "+formattedDate);
    	}
    
    	public void calculateDifference(Date startDate, Date endDate)
    	{
    		/* This is whre i need help! */
    	}
    
    	public static void main(String[] args)
    	{
    		DateFormatter df = new DateFormatter();
    		Scanner sc = new Scanner(System.in);
    		
    		df.displayNow();
    		
    		System.out.println("Please enter a date: ");
    		String date1 = sc.next();
    		System.out.println("Please enter another date: ");
    		String date2 = sc.next();
    	}
    }
    The methods displayNow() and calculateDifference(Date startDate, Date endDate) are essential and cannot be skipped out.

  2. #2
    masijade is offline Senior Member
    Join Date
    Jun 2008
    Posts
    2,571
    Rep Power
    8

    Default

    Calendar, it's setTime, getTime, and add methods, a counter, and a while loop. Check the API for Calendar and attempt something. Once you have something, post it, and we can help you correct it, but we are not going to do it for you.

  3. #3
    rustix is offline Member
    Join Date
    Jul 2008
    Location
    Sri Lanka
    Posts
    2
    Rep Power
    0

    Default

    for the record, i didn't ask anyone to do it for me!

  4. #4
    masijade is offline Senior Member
    Join Date
    Jun 2008
    Posts
    2,571
    Rep Power
    8

    Default

    And
    for the record
    I didn't say you did, I just gave the warning that we wouldn't.

  5. #5
    Norm's Avatar
    Norm is online now Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    16,548
    Rep Power
    23

    Default

    public void calculateDifference(Date startDate, Date endDate)

    It seems like the above mentioned method should return something. If not, what does it do then?

  6. #6
    fishtoprecords's Avatar
    fishtoprecords is offline Senior Member
    Join Date
    Jun 2008
    Posts
    571
    Rep Power
    6

    Default

    In recent versions, the use of Calendar objects instead of Date objects is preferred for uses like this.

    But in either class, the actual date/time value is kept in a long, you can just get the long, and subtract them to get the time difference, and then use an appropriate function (or even just division and mod functions) to convert the milliseconds to days, months, years.

    Get the arithmetic right first, and then use DateFormat to display it.

  7. #7
    masijade is offline Senior Member
    Join Date
    Jun 2008
    Posts
    2,571
    Rep Power
    8

    Default

    Quote Originally Posted by fishtoprecords View Post
    In recent versions, the use of Calendar objects instead of Date objects is preferred for uses like this.

    But in either class, the actual date/time value is kept in a long, you can just get the long, and subtract them to get the time difference, and then use an appropriate function (or even just division and mod functions) to convert the milliseconds to days, months, years.

    Get the arithmetic right first, and then use DateFormat to display it.
    Don't forget to account for the time skew that leads to the leap years. (And that is the exact reason why Calendar is preferred, now. The programmer doesn't need to bother with it.)

  8. #8
    suprabha is offline Member
    Join Date
    Jul 2008
    Posts
    20
    Rep Power
    0

    Default Difference between two dates in years

    Hi all,
    I need java code to get differnce between two given dates

  9. #9
    masijade is offline Senior Member
    Join Date
    Jun 2008
    Posts
    2,571
    Rep Power
    8

    Default

    So write some.

    Hint:

    Calendar and it's add method. (then you start to hammer out the hour/minute/second differences after you have the "days" difference)

  10. #10
    mbnumba6 is offline Member
    Join Date
    Feb 2009
    Posts
    5
    Rep Power
    0

    Default

    Yea I have the same exact question as this thread. The only thing is I want to use the "this" and "that" keyword of java, that is if that is even possible. If you need my whole code for my program I will give it to you.

    Here is my method



    /**
    *To get the difference of number of days
    *in between two dates using "this" and "that"
    * @return diffrenece between two dates
    */
    Java Code:
     if((month >=1) && (month <=12) &&(day > 0) && (day <= daysInMonth(month)))
                   {
                       
                       currentDate = daysInMonth(month);
                       currentDate = this - currentDate ;    
                       
                   }    
                       
                   else 
                   {
                   currentDate = 0;
                   }
                   
                   return this;
                   
                   
              }
    Last edited by mbnumba6; 02-17-2009 at 02:55 AM.

  11. #11
    helloworld111 is offline Member
    Join Date
    Feb 2009
    Posts
    5
    Rep Power
    0

    Default re

    Have a look at this page:
    http : // forums.sun.com/thread.jspa?threadID=488668&forumID=4

    There is some code to calculate date/time differences

  12. #12
    neeraj.singh is offline Member
    Join Date
    Feb 2009
    Location
    Delhi
    Posts
    63
    Rep Power
    0

    Default

    get the day, month, and year of the both dates in int format, and then you can easily compare starting from yr.

    eg:
    if(yr1==y2)
    if(m1==m2)
    if(d1==d2)
    isSameDate = true;

  13. #13
    saurabh1073 is offline Member
    Join Date
    Feb 2009
    Posts
    2
    Rep Power
    0

    Default

    import java.util.*;



    public class DiffDate {
    public static void main(String[] av) {

    Date d1=new Date();
    Date d2=new Date("2009/03/11");
    int difInDays = (int) ((d2.getTime() - d1.getTime())/(1000*60*60*24));
    System.out.println("diffindays"+difInDays);


    }
    }
    Hi. Try to use in this way to find out the difference between two dates.

  14. #14
    masijade is offline Senior Member
    Join Date
    Jun 2008
    Posts
    2,571
    Rep Power
    8

    Default

    Just delving further and further into misinformation.

  15. #15
    mbnumba6 is offline Member
    Join Date
    Feb 2009
    Posts
    5
    Rep Power
    0

    Default

    hmm. Never mind I got mines to work. The only problem is it wont work right if the month has 31, 29, or 28 days in it.

    Java Code:
    public int differnceInDate(int day, int month, int year)
               {
                   int currentDay;
                   int currentMonth;
                   int currentYear;
                   
                   
                   
                   if((month >=1) && (month <=12) &&(day > 0) && (day <= daysInMonth(month)))
                   {
                       
                       currentDay = calendarDay - day;
                       
                       
                       
                       currentMonth = calendarMonth - month;  
                       currentDay = currentMonth * 30 + currentDay;
                       
                       
                       
                       currentYear = calendarYear - year; 
                       currentDay = currentYear * 365 + currentDay;
                       
                       
                   }    
                       
                   else 
                   {
                   currentDay = 0;
                   }
                   
                   return currentDay;
                   
                   
              }

  16. #16
    masijade is offline Senior Member
    Join Date
    Jun 2008
    Posts
    2,571
    Rep Power
    8

    Default

    It's like talking to a wall.

  17. #17
    neeraj.singh is offline Member
    Join Date
    Feb 2009
    Location
    Delhi
    Posts
    63
    Rep Power
    0

    Default

    please refer to the saurabh's post...
    thats the perfect solutions

  18. #18
    Steve11235's Avatar
    Steve11235 is offline Senior Member
    Join Date
    Dec 2008
    Posts
    1,046
    Rep Power
    7

    Default

    Please disregard this post. The logic is incorrect...

    Rustix, after reading down the posts and looking at the API, this is not a simple operation. For whatever reason, Calendar does not provide a difference() method for doing this calculation.

    The first question is: How do you want to express this difference?

    If you just want days, etc., then use Saurabh's method.

    If you want years, month, days, etc., then you need to use GregorianCalendar, which is the only concrete implementation of Calendar, and the fact that a millisecond value of 0 corresponds to 1970.01.01. Note also GregorianCalendar normally defaults to the current time zone, while Date uses GMT. The GregorianCalendar must be forced to use GMT, or you will end up a day off.

    Warning: Always use a positive difference. How you represent that the difference is negative is up to you. I did *not* include any code to check for pDate1 >= pDate2.
    Java Code:
    package test;
    
    import java.util.Date;
    import java.util.GregorianCalendar;
    import java.util.Locale;
    import java.util.TimeZone;
    
    public class DateDifferenceTest {
    	public static void main(String[] args) {
    		final Date date1, date2;
    		date1 = (new GregorianCalendar(2008,
    		    12,
    		    31)).getTime();
    		date2 = (new GregorianCalendar(2007,
    		    11,
    		    30)).getTime();
    		System.out.println(dateDifference(date1,
    		    date2));
    	}
    
    	public static String dateDifference(final Date pDate1,
    	    final Date pDate2) {
    		final String diffString;
    		long difference = 0;
    		GregorianCalendar gc = null;
    		gc = new GregorianCalendar();
    		gc.setTimeZone(TimeZone.getTimeZone("GMT"));
    		gc.setTimeInMillis(pDate1.getTime()
    		    - pDate2.getTime());
    		diffString = (gc.get(GregorianCalendar.YEAR) - 1970)
    		    + "."
    		    + (gc.get(GregorianCalendar.MONTH))
    		    + "."
    		    + (gc.get(GregorianCalendar.DAY_OF_MONTH) - 1);
    		return diffString;
    	}
    }
    Last edited by Steve11235; 02-19-2009 at 03:28 AM. Reason: Bad logic provided

  19. #19
    masijade is offline Senior Member
    Join Date
    Jun 2008
    Posts
    2,571
    Rep Power
    8

    Default

    If you do setTime(Date) with the Calendar, you do not end up a day off. And using getTime() on the Calendar to compare to the original date you are also not a "day off", as that returns a Date object. Use two Calendars for start and end date, and the point becomes completely moot.

  20. #20
    Steve11235's Avatar
    Steve11235 is offline Senior Member
    Join Date
    Dec 2008
    Posts
    1,046
    Rep Power
    7

    Default

    Apparently, you didn't test the code I provided. You are correct in saying "not a day off", it is more like, the time zone adjustment off. However, for those of us west of the Prime Meridian, that puts us a few hours early. Since "dates" are normally entered without minutes, that puts the calendar several hours early, resulting in a value that, when truncated to year.month.day, is a day off.

    The point is not moot; I found it because the results were a day off. I corrected it by setting the calendar time zone to GMT.

Page 1 of 2 12 LastLast

Similar Threads

  1. How to Compare two Dates
    By Java Tip in forum java.util
    Replies: 1
    Last Post: 06-24-2008, 07:05 AM
  2. No fo days between two dates
    By Java Tip in forum Java Tip
    Replies: 0
    Last Post: 01-28-2008, 09:06 AM
  3. Comparing dates
    By Java Tip in forum Java Tip
    Replies: 0
    Last Post: 01-28-2008, 09:02 AM
  4. Inbetween Dates
    By Rageagainst20 in forum New To Java
    Replies: 4
    Last Post: 12-19-2007, 05:24 AM
  5. help with dates and time
    By osval in forum New To Java
    Replies: 3
    Last Post: 12-12-2007, 12:41 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •