comparing two dates/times in java


DevX Home    Today's Headlines   Articles Archive   Tip Bank   Forums   

Results 1 to 3 of 3

Thread: comparing two dates/times in java

  1. #1
    Join Date
    May 2005
    Posts
    3

    comparing two dates/times in java

    Hi,

    i am trying to compare two dates and times and wish to return the difference in minutes as an integer. both date/times are stored in a timestamp e.g. 2005-01-01 22:10:35.

    does anybody know how to do this in java or have any sample code i could try.

    thanks in advance,

    scoobie

  2. #2
    Join Date
    Nov 2004
    Location
    Norway
    Posts
    1,560

    Like this:

    Code:
    /**
     * Date difference, as minutes (abs)
     */
    import java.util.*;
    import java.text.*;
    import javax.swing.text.*;
    
    public class DateDiff {
    
      static SimpleDateFormat df=new SimpleDateFormat("yyyy-mm-dd hh:mm:ss");
      
      private String sD1;
      private String sD2;
    
      public DateDiff(String sD1, String sD2) {
        this.sD1=sD1;
        this.sD2=sD2;
      }
      /**
       * Parse date strings in format like: 2005-01-01 22:10:35
       */
      public long getDifferenceInMinutes () throws ParseException {
        Date d1=df.parse(sD1);
        Date d2=df.parse(sD2);
        long d1Ms=d1.getTime();
        long d2Ms=d2.getTime();
        return Math.abs((d1Ms-d2Ms)/60000);
      }
      /**
       ***************** MAIN *******************
       * @param args
       */
      public static void main(String[] args) {
        DateDiff dd = new DateDiff("2005-01-01 22:10:35",
                                   "2005-01-01 23:11:35");
        try {
          long diff=dd.getDifferenceInMinutes();
          System.out.println("Time difference (abs): " + diff);
        }
        catch (ParseException ex) {
          ex.printStackTrace();
        }
      }
    }
    Last edited by sjalle; 05-10-2005 at 03:57 AM.
    eschew obfuscation

  3. #3
    Join Date
    May 2005
    Posts
    3
    thanks for all your help, that worked great

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
HTML5 Development Center
 
 
FAQ
Latest Articles
Java
.NET
XML
Database
Enterprise
Questions? Contact us.
C++
Web Development
Wireless
Latest Tips
Open Source


   Development Centers

   -- Android Development Center
   -- Cloud Development Project Center
   -- HTML5 Development Center
   -- Windows Mobile Development Center