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