wzieba
wzieba

Reputation: 414

Subtracting two dates in Java

I want to subtract two dates (one constant and one current) in Java but I've got strange problems with it. Here is the code :

DateFormat df = new SimpleDateFormat("HH:MM");
Date FirstLessonInterval=df.parse("08:45");
Date currentTime = new Date();

long diff = FirstLessonInterval.getTime()-currentTime.getTime();

String s = String.valueOf(diff);
LessonOrBreak=(diff);

I've got minus minutes. When I want to see FirstLessonInterval with FirstLessonInterval.toString() it shows the year 1970. What can I do?

Upvotes: 1

Views: 1857

Answers (7)

user7349838
user7349838

Reputation:

    String startDateString = "2017-03-08";
    String finishDateString = "2017-03-10";        

    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd", Locale.ENGLISH);
    LocalDate startDate = LocalDate.parse(startDateString, formatter);
    LocalDate finishDate = LocalDate.parse(finishDateString, formatter);

Integer day = finishDate.compareTo(startDate);

Integer day will be 3. It means that the difference between two dates equals 3 days

Upvotes: 0

Basil Bourque
Basil Bourque

Reputation: 338316

Missing Date Portion

As the other correct answers said, you are using the java.util.Date class which is a date-time class holding both a date portion and a time portion.

LocalTime

If you truly care about only time of day, with no date and no time zone, then use the LocalTime class found in both the Joda-Time library and the new java.tome package in Java 8. By the way the old java.util.Date and .Calendar classes are notoriously troublesome and should be avoided.

Joda-Time

Here is some code with date-time and time zone.

Using the Joda-Time 2.3 library…

DateTimeZone timeZone = DateTimeZone.forID( "Europe/Warsaw" );
DateTime dateTime = new DateTime( 2014, 1, 2, 8, 45, 0, timeZone );
DateTime now = new DateTime( 2014, 1, 2, 8, 30, 0, timeZone ); // Or DateTime.now( timeZone )
Duration duration = new Duration( dateTime, now );  // or use Period or Interval.

Joda-Time offers intelligent classes and methods of working with a span of time (a Period, Interval, or Duration). For example look at the Minutes class. But if all you need is millseconds, here you go.

long millis = duration.getMillis();

Upvotes: 1

java_noob
java_noob

Reputation: 1

I dont know if this way is efficient or not but it's an idea anyway:

Date curr = new Date();
Date date = new Date(114,     /*114 is 2014 , don't know why*/ 
                     6, 
                     16, 
                     8, 45, 0);

System.out.println(curr); 
System.out.println(date);  

Date x = new Date(curr.getYear() - date.getYear() ,
        curr.getMonth() - date.getMonth(),
        curr.getDate() - date.getDate(),
        curr.getHours() - date.getHours(),
        curr.getMinutes() - date.getMinutes(),
        curr.getSeconds() - date.getSeconds()   );

Upvotes: 0

bcorso
bcorso

Reputation: 47068

The problem is that you are not providing enough info to SimpleDateFormat. It sets the hour and minutes correctly but nothing else.

DateFormat df = new SimpleDateFormat("HH:mm");
System.out.println(df.parse("08:45"));          // Thu Jan 01 08:45:00 GMT 1970
System.out.println(new Date());                 // Sun May 11 07:52:50 GMT 2014

If you want your date to be with respect to the current date try this:

Date curr = new Date();
Date date = new Date(curr.getYear(), 
                     curr.getMonth(), 
                     curr.getDate(), 
                     8, 45, 0);

System.out.println(date);                       // Sun May 11 08:45:00 GMT 2014
System.out.println(curr);                       // Sun May 11 07:52:50 GMT 2014

long diff = date.getTime() - curr.getTime();
System.out.println("Minutes: " + diff/6000);    // Minutes: 53

Upvotes: 0

StoopidDonut
StoopidDonut

Reputation: 8617

  1. Your format pattern is incorrect, use lower case mm to represent minutes
  2. When you do not specify much details to the outdated Java date api, it considers the time since UNIX epoch (1st Jan 1970)
  3. Since you are assuming the date to be the same as the constant time parameters you provide and independent of the timezones, you can bring your current date comparable to the time since UNIX epoch:

Staying close to your original code;

DateFormat df = new SimpleDateFormat("HH:mm");
Date firstLessonInterval = df.parse("08:45");
Date currentTime = new Date();

// Format the current date comparable to UNIX epoch (only hold time params)
String dateStr = df.format(currentTime.getTime());
// Parse the modified date string to a date object
Date comDate = df.parse(dateStr);
// Take the difference in millis
long diff = firstLessonInterval.getTime() - comDate.getTime();
String s = String.valueOf(diff);
// Print the number of minutes passed since
System.out.println("Minutes {elapsed since/time to} 08:45 - " + Math.abs(diff) / 1000 / 60);

Upvotes: 1

Patrick
Patrick

Reputation: 35224

You forgot to give a date, you just defined a time:

DateFormat df = new SimpleDateFormat("HH:MM");
Date FirstLessonInterval=df.parse("08:45");

and this is in unix time day 0 which is the 1.1.1970

try something like

DateFormat df = new SimpleDateFormat("yyyy/MM/dd HH:MM");
Date FirstLessonInterval=df.parse("2014/05/10 08:45");

Upvotes: 3

RNJ
RNJ

Reputation: 15552

1970 is where all time began according to computers. Are we missing some code in your question? You can faff around with the current time in milliseconds but i'd take a look at JodaTime and use that.

The reason you are getting 1970.... is because I suspect your diff is quite a small number. Then if you look at that as a date then it will be a small number + 1 Jan 1970 which will still be in 1970. But as i said I suspect we are missing some code in your question.

In JodaTime you can do somethign like the below but im not sure what it is you are exactly after

Interval i= new Interval(new DateTime(FirstLessonInterval), new DateTime());
System.out.println("Interval is: " + i.toDurationMillis());

Upvotes: 1

Related Questions