skip to Main Content

I have this function to print out dates or minutes/hours from tweets. It works fine but dates are in English. How can I change the months into e.g. Spanish? The date format is fixed – it comes from the Twitter API.
It looks like this:

var $time = "Fri May 04 20:33:17 +0000 2018";

function relative_time(time_value) {
      // How can I apply these months to the function?
      //var months = Array('Enero', 'Febrero', 'Marzo', 'Abril', 'Mayo', 'Junio', 'Julio', 'Agosto', 'Septiembre', 'Octubre', 'Noviembre', 'Diciembre');

      var values = time_value.split(" ");
      time_value = values[1] + " " + values[2] + ", " + values[5] + " " + values[3];
      var parsed_date = Date.parse(time_value);
      var relative_to = (arguments.length > 1) ? arguments[1] : new Date();
      var delta = parseInt((relative_to.getTime() - parsed_date) / 1000);
      var shortdate = time_value.substr(4, 2) + " " + time_value.substr(0, 3);
      delta = delta + (relative_to.getTimezoneOffset() * 60);

      if (delta < 60) {
        return '1m';
      } else if (delta < 120) {
        return '1m';
      } else if (delta < (60 * 60)) {
        return (parseInt(delta / 60)).toString() + 'm';
      } else if (delta < (120 * 60)) {
        return '1h';
      } else if (delta < (24 * 60 * 60)) {
        return (parseInt(delta / 3600)).toString() + 'h';
      } else if (delta < (48 * 60 * 60)) {
        //return '1 day';
        return shortdate;
      } else {
        return shortdate;
      }
    }

Check out Fiddle here.

3

Answers


  1. var date = new Date('Fri May 04 20:33:17 +0000 2018');
    var months= ['Enero', 'Febrero', 'Marzo', 'Abril', 'Mayo', 'Junio', 'Julio', 'Agosto', 'Septiembre', 'Octubre', 'Noviembre', 'Diciembre'];
    var outDate= date.getDate()+ ' '+ months[date.getMonth()];
    
    Login or Signup to reply.
  2. With moment.JS : viernes, 4 de mayo de 2018 22:33

    const $time = "Fri May 04 20:33:17 +0000 2018";
    
    const myDate = new Date($time);
    const myMoment = moment(myDate);
    
    document.body.innerHTML = myMoment.format('LLLL');
    <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.19.1/moment.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.1/locale/es.js"></script>
    Login or Signup to reply.
  3. var $time = "Fri May 04 20:33:17 +0000 2018";
    
    function relative_time(time_value) {
        var date = new Date(time_value);
        var months= ['Enero', 'Febrero', 'Marzo', 'Abril', 'Mayo', 'Junio', 'Julio', 
        'Agosto', 'Septiembre', 'Octubre', 'Noviembre', 'Diciembre'];
        return date.getDate()+ ' '+ months[date.getMonth()];
       }
    
    relative_time($time);
    

    Does this answer your question?

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search