Advertisement
Guest User

Untitled

a guest
Sep 5th, 2015
104
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.64 KB | None | 0 0
  1. // Aquí guardo el tiempo.
  2.     mp.getLongs().put(item.getName(), new Date().getTime());
  3.  
  4. // Así hago un check de si ya ha pasado el tiempo y si no, obtengo lo que falta
  5.     long timestampNow = System.currentTimeMillis() / 1000;
  6.     long expires = mp.getLongs().get(item.getName());
  7.     if(timestampNow >= expires){
  8.           mp.getLongs().remove(item.getName());
  9.     }else{
  10.           expires = (long) expires * 1000;
  11.           String formatExpires = Utils.formatDateDiff(expires);
  12.     }
  13. // Esto me devuelve un String con el tiempo dividido en años, meses, días, horas, minutos y segundos:
  14.     public static String formatDateDiff(Calendar fromDate, Calendar toDate){
  15.           boolean future = false;
  16.  
  17.           if (toDate.equals(fromDate)) {
  18.             return "1 segundo";
  19.           }
  20.           if (toDate.after(fromDate)) {
  21.             future = true;
  22.           }
  23.  
  24.         StringBuilder sb = new StringBuilder();
  25.         int[] types = new int[] { Calendar.YEAR, Calendar.MONTH, Calendar.DAY_OF_MONTH, Calendar.HOUR_OF_DAY, Calendar.MINUTE, Calendar.SECOND };
  26.         String[] names = new String[] { "año", "años", "mes", "meses", "día", "días", "hora", "horas", "minuto", "minutos", "segundo", "segundos" };
  27.         for (int i = 0; i < types.length; i++) {
  28.             int diff = dateDiff(types[i], fromDate, toDate, future);
  29.             if (diff > 0) {
  30.                 sb.append(" ").append(diff).append(" ").append(names[i * 2 + (diff > 1 ? 1 : 0)]);
  31.             }
  32.         }
  33.         if (sb.length() == 0) {
  34.             return "1 segundo";
  35.         }
  36.         return sb.toString().trim();
  37.     }
  38.  
  39.     public static String formatDateDiff(long date) {
  40.         Calendar now = new GregorianCalendar();
  41.         Calendar c = new GregorianCalendar();
  42.         c.setTimeInMillis(date);
  43.         return formatDateDiff(now, c);
  44.     }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement