1

I am trying to figure out how to calculate the time difference between two dates in milliseconds.

I found this piece of code (https://stackoverflow.com/a/39129969/8921111) from another cn1 question, but when I send an Android build, I receive error for the method set().

error: method set in class Calendar cannot be applied to given types;

Here is the code:

DateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy");
try {
    java.util.Calendar now = java.util.Calendar.getInstance();
    now.set(now.get(java.util.Calendar.YEAR), now.get(java.util.Calendar.MONTH), now.get(java.util.Calendar.DATE), 0, 0, 0);
    now.set(java.util.Calendar.MILLISECOND, 0);

    java.util.Calendar otherDate = java.util.Calendar.getInstance();
    otherDate.setTime(dateFormat.parse("6/28/2021"));
    otherDate.set(otherDate.get(java.util.Calendar.YEAR), otherDate.get(java.util.Calendar.MONTH), otherDate.get(java.util.Calendar.DATE), 0, 0, 0);
    otherDate.set(java.util.Calendar.MILLISECOND, 0);

           
    long num =otherDate.getTime().getTime()- now.getTime().getTime();
    Log.p("The long millis expiration is in "+ (long) (num));
} catch (ParseException ex) {
    return -999999;
}

Will appreciate your help.

fnklstn
  • 492
  • 4
  • 16
  • 2
    Q: How to calculate time difference in milliseconds. A: Just subtract one from the other! ALSO: 1) Exactly which "Calendar.set()" line is giving the error? It's probably because you're passing invalid arguments to that call. 2) What's the deal with `otherDate.getTime().getTime()- now.getTime().getTime()`? Doesn't that seem a bit duplicate redundant? Why not call .getTimeInMillis()? 3) Why not use Java8 time APIs? – paulsm4 May 26 '21 at 21:54
  • @paulsm4 you should submit this as as the answer (without the Java 8 time APIs which aren't yet supported in cn1). Specifically it's: `long mil = System.currentTimeMillis() - dateFormat.parse("6/28/2021").getTime();` or `long mil = myDate.getTime() - dateFormat.parse("6/28/2021").getTime();` – Shai Almog May 27 '21 at 01:39
  • @paulsm4 Not all Java libraries are supported by cn1. Therefore I thought it could be useful to post the question on the forum. – fnklstn May 27 '21 at 13:01
  • Both set() methods with 6 args are giving an error, so you are right, it's because only 2 are expected. However, in Java docs there is a set() method with 6 args, and it compiles properly. Just doesn't build. – fnklstn May 27 '21 at 15:54

0 Answers0