Search code examples
javadatetimetalend

How can I retrieve the difference between two Date instances in minutes?


According to the Talend docs, it is possible to calculate the difference between two dates using TalendDate.dateDiffFloor up to seconds and milliseconds.

However, the docs don't say how (or which format parameter has to be specified).

I have to get this value in seconds as it will feed into a tInfiniteLoop component.

I have tried with "mmmm" and "mm" with no luck. In that case I get the error:

Exception in component tMap_3
java.lang.RuntimeException: Can't support the dateType: mm ,please try "yyyy" or "MM"
    at routines.TalendDate.diffDateFloor(TalendDate.java:661)
    at timeouttester.job_2_0_1.job_2.tInfiniteLoop_2Process(job_2.java:1156)
    at timeouttester.job_2_0_1.job_2.runJobInTOS(job_2.java:1616)
    at timeouttester.job_2_0_1.job_2.main(job_2.java:1464)

Which argument do I have to specify to get minutes? And, if not doable, maybe there is a workaround doing this in "vanilla" Java if not possible via Talend?

I am currently using the following statement in a tMap component:

TalendDate.diffDateFloor(TalendDate.parseDateInUTC("EEE, d MMM yyyy HH:mm:ss", Var.expires), TalendDate.getCurrentDate(), "mmmm") 

Solution

  • I have no clue about Talend but as you said vanilla is also possible for you: You may use the class Duration which represents the duration between two objects of type Temporal. Such a temporal class would, for example, be Instant which is a snapshot on the time line. Instant has great support in the API. You can retrieve one from Date#toInstant, or from Calendar#toInstant and more.

    See this small example:

    Date dateBefore = new GregorianCalendar(2014, Calendar.FEBRUARY, 11).getTime();
    
    Instant before = dateBefore.toInstant();
    Instant now = Instant.now();
    
    Duration duration = Duration.between(before, now);
    System.out.println("Days: " + duration.toDays());
    

    However, If I'm not mistaken the class Instant itself is only precise down to milliseconds. If that is not enough, you may use another class which implements Temporal or create your own.

    For your application, you are probably interested in:

    Duration#toMinutes()
    Duration#toMillis()
    

    Note that the returned value (long) of those methods are rounded downwards (floor). So if the real amount of minutes where something like 1.453, toMinutes() will return 1 and toMillis() returns 1453.