Format timestamp with Javascript

0

I have tried in many ways, and none of them work for me. It's simple what I want to achieve, I do not know if it's easy to do it.

I want to transform, this:

1510060016 // time() -> PHP

In this

Hace 1 hora

My idea was to do something like this

<div time="1510060016"></div>

And in Javascipt you can take the value of time to modify it every 10s with setInterval ();

Obviously, I need you to say: Instanstes ago, 1 hour ago, 1 day ago, 2 days ago, etc.

What can I do?

    
asked by Axel Benitez 07.11.2017 в 15:22
source

2 answers

0

I'll give you an example with moment.js , if you do not want to use the excellent response of the colleague @Asier

<!DOCTYPE html>
<html>

  <head>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.19.1/moment.js"></script>
  </head>

  <body>
    <button type="button" id="button">Obtener tiempo</button>
    
    <script>
      $(document).ready(function(){
        $("#button").click(function(){
          alert(moment(1510060016 * 1000).fromNow());
        });
      });
    </script>
  </body>
</html>
    
answered by 07.11.2017 / 16:02
source
2

Here is an example without using a library:

function updateTimes(){
  // Seleccionamos elementos con atributo time
  var times = document.querySelectorAll('[time]');
  // Calculamos nº de segundos de la fecha actual
  var now = Math.floor((new Date()).getTime() / 1000);
  // Por cada elemento (div)
  times.forEach(function(item){
    // Calculamos la diferencia respecto a la fecha actual
    var diff = now - parseInt(item.getAttribute('time'));
    // En función del valor mostramos el dato en segundos, minutos, horas o días
    if (diff < 60){
      item.innerText = 'Hace ' + diff + ' segundos';
      return;
    }
    diff = Math.floor(diff / 60);
    if (diff < 60){
      item.innerText = 'Hace ' + diff + ' minutos';
      return;
    }
    diff = Math.floor(diff / 60);
    if (diff < 24){
      item.innerText = 'Hace ' + diff + ' horas';
      return;
    }
    diff = Math.floor(diff / 24);
    item.innerText = 'Hace ' + diff + ' días';
  });
}

updateTimes();
setInterval(updateTimes, 10000);
<div time="1510060016"></div>
<div time="1510065371"></div>
    
answered by 07.11.2017 в 15:37