JoseXS
9/29/2017 - 3:41 PM

Time Ago

[Javascript] fecha a formato TimeAgo (hace x minutos)

const timeAgo = (time) => {
    switch (typeof time) {
      case 'number': break;
      case 'string': time = +new Date(time); break;
      case 'object': if (time.constructor === Date) time = time.getTime(); break;
      default: time = +new Date();
    }
    let time_formats = [
      [60, 'segundos', 1], // 60
      [120, '1 minuto', 'En 1 minuto'], // 60*2
      [3600, 'minutos', 60], // 60*60, 60
      [7200, '1 hora', 'En 1 hora'], // 60*60*2
      [86400, 'horas', 3600], // 60*60*24, 60*60
      [172800, '1 dia', 'Mañana'], // 60*60*24*2
      [604800, 'dias', 86400], // 60*60*24*7, 60*60*24
      [1209600, '1 semana', 'Dentro de 1 Semana'], // 60*60*24*7*4*2
      [2419200, 'semanas', 604800], // 60*60*24*7*4, 60*60*24*7
      [4838400, '1 mes', 'Dentro de 1 Mes'], // 60*60*24*7*4*2
      [29030400, 'meses', 2419200], // 60*60*24*7*4*12, 60*60*24*7*4
      [58060800, '1 año', 'Dentro de 1 Año'], // 60*60*24*7*4*12*2
      [2903040000, 'años', 29030400], // 60*60*24*7*4*12*100, 60*60*24*7*4*12
    ];
    let seconds = (+new Date() - time) / 1000, token = '', list_choice = 1;

    if (seconds == 0) {
      return 'Ahora Mismo'
    }
    if (seconds < 0) {
      seconds = Math.abs(seconds);
      token = '';
      list_choice = 2;
    }
    let i = 0, format;
    while (format = time_formats[i++])
      if (seconds < format[0]) {
        if (typeof format[2] == 'string')
          return format[list_choice];
        else
          return token + ' ' + Math.floor(seconds / format[2]) + ' ' + format[1];
      }
    return time;
  }