简体   繁体   中英

How to perform arithmetic on java.sql.Time objects?

I have some java.sql.Time objects as follows:

    String s1 = "12:00:04";
    String s2 = "12:23:34";
    String s3 = "12:03:02";
    String s4 = "11:00:54";

    int dij = j-i;
    int dmj = j-m;
    java.sql.Time tdi = java.sql.Time.valueOf(s1);
    java.sql.Time tki = java.sql.Time.valueOf(s2);
    java.sql.Time tdm = java.sql.Time.valueOf(s3);
    java.sql.Time tdj = java.sql.Time.valueOf(s4);

How can I perform subtract operations of these objects? I want to get the result in java.sql.Time object itself but number of seconds will work too. Most of the methods given in java.sql.Time class are deprecated. http://docs.oracle.com/javase/7/docs/api/java/sql/Time.html

Since java.sql.Time wraps a java.util.Date , I'm not sure that subtraction and putting the result in a java.sql.Time object is meaningful .

I would rather perform the subtraction (most likely using the milliseconds field and the getTime accessor), and store the result as a numeric representing the number of seconds/milliseconds etc.

If you're performing a lot of arithmetic, the solution is most likely to look at Joda-Time . See the FAQ for arithmetic-related info. Joda-Time has a more consistent and useful API, plus is thread-safe (unlike the standard java.util.Date/Calendar )

I suggest you tu use the Joda Time java library which is very good at handling dates and times in Java.

example:

public boolean isRentalOverdue(DateTime datetimeRented) {
  Period rentalPeriod = new Period().withDays(2).withHours(12);
  return datetimeRented.plus(rentalPeriod).isBeforeNow();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM