DateUtils.java

  1. package common;

  2. import java.time.Instant;
  3. import java.time.LocalDate;
  4. import java.time.ZoneId;
  5. import java.time.temporal.ChronoUnit;

  6. /**
  7.  * Classe di utilità contenente funzioni per la stampa di date nella view
  8.  */
  9. public final class DateUtils {
  10.     /**
  11.      * <p>Questa funzione restituisce un messaggio indicante il tempo trascorso tra il tempo di invocazione del metodo al tempo
  12.      * passato come parametro.</p>
  13.      * <p>Ad esempio, se il tempo passato come parametro corrisponde al 05/03/2022 16:00:00Z e il metodo è stato invocato alle
  14.      * 16:00:05 dello stesso giorno, il metodo restituirà una stringa contenente "5 secondi fa"</p>.
  15.      * @param then Il tempo di riferimento
  16.      * @return Il messaggio "x secondi/minuti/ore/giorni/mesi/anni fa"
  17.      */
  18.     public static String printTimeSince(Instant then){
  19.         long n;
  20.         if ((n = Math.abs(Instant.now().until(then, ChronoUnit.SECONDS))) < 60){
  21.             return n == 1 ? n + " secondo" : n + " secondi";
  22.         } else if ((n = Math.abs(Instant.now().until(then, ChronoUnit.MINUTES))) < 60){
  23.             return n == 1 ? n + " minuto" : n + " minuti";
  24.         } else if ((n = Math.abs(Instant.now().until(then, ChronoUnit.HOURS))) < 24){
  25.             return n == 1 ? n + " ora" : n + " ore";
  26.         } else if ((n = Math.abs(Instant.now().until(then, ChronoUnit.DAYS))) < 30) {
  27.             return n == 1 ? n + " giorno" : n + " giorni";
  28.         } else if ((n = Math.abs(Instant.now().until(then, ChronoUnit.DAYS))) < 365) {
  29.             n /= 30;
  30.             return n == 1 ? n + " mese" : n + " mesi";
  31.         } else {
  32.             int thenYear = then.atZone(ZoneId.systemDefault()).toLocalDate().getYear();
  33.             n = Math.abs(thenYear - LocalDate.now().getYear());
  34.             return n == 1 ? n + " anno" : n + " anni";
  35.         }
  36.     }
  37. }