1

I want subtract 2 dates and saving the difference:

SimpleDateFormat formatter = new SimpleDateFormat("HH:mm");
Date a = formatter.parse("08:06");
Date b = formatter.parse("08:00");
Date asd =  new Date(a.getTime() - b.getTime());

The problem is that asd is not 00:06, but 01:06 (Thu Jan 01 01:06:00 CET 1970), I think that this depend on timezone. But how do I solve this? Should I change the jvm timezone?

7
  • 3
    A Date is not the same as an interval. Mar 16, 2014 at 16:13
  • 2
    The JDK has nothing like that; you should use Joda Time and its Interval.
    – fge
    Mar 16, 2014 at 16:18
  • Should I use something else? I heard joda.org/joda-time but does it exist something that fit better in the Java sdk? Mar 16, 2014 at 16:18
  • yes, joda-time is much better than java 7 dates but worse than java 8 Date and Time API. Java 8 will be released in 2 days but you can already download and use it now. Mar 16, 2014 at 16:21
  • @SauliusŠimčikas " worse than java 8 Date and Time API." <-- how so? Are you aware that Java 8's new date API is 90+% inspired by Joda Time?
    – fge
    Mar 16, 2014 at 16:51

4 Answers 4

4

Note the javadoc of the Date(long) constructor

Allocates a Date object and initializes it to represent the specified number of milliseconds since the standard base time known as "the epoch", namely January 1, 1970, 00:00:00 GMT.

This is not an interval.

Joda-Time does provide an Interval class to perform such calculations. Java 8 should also have such a class when it comes out.

3
long difference = a.getTime() - b.getTime();
int hours = (int) (difference / 3600000);
int minutes = (int) (difference % 3600000 / 60000);
String formatted = String.format("%02d:%02d", hours, minutes);
1
  • This don't work if: long difference = a.getTime() - b.getTime() - c.getTime(); Maybe is better to use Joda Time... Mar 16, 2014 at 21:33
1

Span of Time

Your question is not clear. Apparently you want to work with a span of time. For that you definitely need the Joda-Time library (or the new java.time package built into Java 8).

Joda-Time

Joda-Time offers 3 classes for spans of time:

  • Interval
    Represents a start-stop pair of points along the timeline. Example: 2013-01-01T00:00:00.000-05:00/2013-01-04T18:00:00.000-05:00
  • Duration
    A length of time in milliseconds. Not tied to the timeline.
  • Period
    Represents a span as a number of fields, such as years, months, weeks, days, hours, minutes, seconds and millis.

ISO 8601

The ISO 8601 standard defines sensible textual formats to represents various aspects of date-time values. Joda-Time (and java.time in Java 8) use ISO 8601 as its defaults.

In particular, ISO 8601 defines a format for Durations (what Joda-Time calls a Period†). A value is represented as a string in the format of PnYnMnDTnHnMnS. The 'P' indicates the beginning of a duration (Period) string. A 'T' indicates the time portion. Each number precedes its element designator. For example, "P3Y6M4DT12H30M5S" represents a duration of "three years, six months, four days, twelve hours, thirty minutes, and five seconds".

Example Code

// Specify the time zone rather than rely on default. https://en.wikipedia.org/wiki/List_of_tz_database_time_zones
DateTimeZone timeZone = DateTimeZone.forID( "Europe/Rome" );
DateTime a = new DateTime( 2014, 1, 2, 8, 6, 0, timeZone );
DateTime b = new DateTime( 2014, 1, 2, 8, 0, 0, timeZone );
Period period = new Period( a, b);
long millis = period.toStandardDuration().getMillis();

Dump to console…

System.out.println( "a: " + a );
System.out.println( "b: " + b );
System.out.println( "period: " + period );
System.out.println( "millis: " + millis );

When run…

a: 2014-01-02T08:06:00.000+01:00
b: 2014-01-02T08:00:00.000+01:00
period: PT-6M
millis: -360000

More Info

Search StackOverflow for "joda" and one of those three class names to find many examples.


†Time-related terms vary widely in their usage and meaning. A new standards proposal to normalize such terms has begun. But, for now, get used to having to "translate" the terms when switching contexts.

2
  • I need to work just with HH:mm. Would be useful have this too: 18:30 - 18:40 = -00:10 Mar 16, 2014 at 21:37
  • @Accollativo (a) I added example code to illustrate. (b) You would have found such examples if you had searched StackOverflow. (c) Invest some time in study. Date-time work is surprisingly complicated and tricky. Mar 16, 2014 at 22:56
0

Thanks for all your solution, it will be useful to my next projects.

But I don't need all the stuff inside Joda, I need just something of lightweight to sum and subtract time (and have negative time), so I take few minutes to create my own class for time handling.

Use this freely:

public class Time {

    private int hours;
    private int minutes;
    private long totalMinutes;

    public Time()
    {
        hours = 0;
        minutes = 0;
        totalMinutes = 0;
    }

    public Time(String time) throws RuntimeException
    {
        try
        {
            String[] items = time.split(":");
            this.hours = Integer.parseInt(items[0]);
            this.minutes = Integer.parseInt(items[1]);
            this.totalMinutes = hours*60+minutes;
        }
        catch (RuntimeException re)
        {
            throw new RuntimeException("Parsing time error", re);
        }
    }

    public Time(Time time)
    {
        this.hours = time.hours;
        this.minutes = time.minutes;
        this.totalMinutes = time.totalMinutes;
    }

    public Time add(Time val)
    {
        Time ret = new Time(this);
        ret.totalMinutes += val.totalMinutes;
        ret.hours = (int) Math.abs( (long)ret.totalMinutes/60 );
        ret.minutes = (int) Math.abs( (long)ret.totalMinutes%60 );
        return ret;
    }

    public Time sub(Time val)
    {
        Time ret = new Time(this);
        ret.totalMinutes -= val.totalMinutes;
        ret.hours = (int) Math.abs( (long)ret.totalMinutes/60 );
        ret.minutes = (int) Math.abs( (long)ret.totalMinutes%60 );
        return ret;
    }

    public int getHours() {
        return hours;
    }

    public void setHours(int hours) {
        this.hours = hours;
    }

    public int getMinutes() {
        return minutes;
    }

    public void setMinutes(int minutes) {
        this.minutes = minutes;
    }

    @Override
    public String toString() 
    {
        StringBuilder tmpHHmm = new StringBuilder("" + hours);
        if (totalMinutes<0)
        {
            tmpHHmm.insert(0, "-");
        }
        if (hours<10)
        {
            tmpHHmm.insert(tmpHHmm.length()-1, "0");
        }
        tmpHHmm.append(":"+minutes);
        if (minutes<10)
        {
            tmpHHmm.insert(tmpHHmm.length()-1, "0");
        }
        return tmpHHmm.toString();
    }

    public long getTotalMinutes() {
        return totalMinutes;
    }

    public void setTotalMinutes(long totalMinutes) {
        this.totalMinutes = totalMinutes;
    }

}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.