Extract data separately from a date in string format

Asked

Viewed 230 times

2

I have a date in string format:

Wed Jul 20 2016 14:01:01 GMT-0300 (BRT)

And I would like to extract the date and days and time in such a way that I can form a string like this:

Quarta-Feira, 20-07-2016 as 17:01

  • You have to set locale in javascript to en-BR but I recommend using a library to manipulate dates. http://momentjs.com/

  • Yeah, I know this library, but I couldn’t find any method of it.

  • I updated the code in my reply. I got a bug where the hours could be longer than 23, I just modified that line: " às " + (parseFloat(date.time.hours) + 3) + ":" + date.time.minutes; for " às " + ((parseFloat(date.time.hours) + 3) % 24) + ":" + date.time.minutes;. Now you’re safer.

  • 1

    Great, thank you very much. Please, if you know and have time, you could put an answer if I have a date in this format: 2016-07-20T15:01:01-02:00, and with the same answer: Quarta-Feira, 20-07-2016 as 15:01. @Theprohands

3 answers

2

If the idea is to present a more beautiful date to the user, there is a simpler way to do, in a similar but different format:

//se a data fosse: new Date('Tue Aug 02 2016 15:28:14 GMT-0300 (BRT)');
 var data = new Date();

    var options = {
        weekday: "long", year: "numeric", month: "long",
        day: "2-digit", hour: "2-digit", minute: "2-digit"
    }
//terça-feira, 02 de agosto de 2016 15:28
data.toLocaleDateString('pt-BR', options);

And if you’re going to format it in the wood you want, it would be basically like this:

var data = new Date();

var optionsWeek = {
    weekday: "long"
}

 var hourMinute = {
     day: "2-digit", hour: "2-digit", minute: "2-digit"
 }

 var week = data.toLocaleDateString('pt-BR', optionsWeek);
 var hm = data.toLocaleDateString('pt-BR', hourMinute);
 var dateFormatted = data.toLocaleDateString('pt-BR')
                      .replace(/\//g,'-');
 var sDate = (week.substr(0,1)).toUpperCase() + 
          week.substr(1) + ', ' + 
          dateFormatted + ' as ' + 
          hm.substr(3);

console.log(sDate);

1

Here is what you asked to +. Now you can convert 2 correct style dates 2016-07-20T15:01:01-02:00 and style Wed Jul 20 2016 14:01:01 GMT-0300 (BRT).

Date.toBrazilianFormat = (function() {

    // Dias da semana (de inglês abreviado para português)
    var weeks = {
        "Sun": "Domingo",
        "Mon": "Segunda-feira",
        "Tur": "Ter\xe7a-feira",
        "Wed": "Quarta-feira",
        "Thu": "Quinta-feira",
        "Fri": "Sexta-feira",
        "Sat": "S\xe1bado"
    },
    // Número sequencial dos meses do ano
     monthies = {
        "Jan": 1,
        "Feb": 2,
        "Mar" : 3,
        "Apr" : 4,
        "May" : 5,
        "Jun" : 6,
        "Jul" : 7,
        "Aug" : 8,
        "Sep" : 9,
        "Oct" : 10,
        "Nov" : 11,
        "Dec" : 12
    };

    return (function(date) {

        if(typeof date !== 'string')
            date = 'Sun Jan 10 1999 14:01:01 GMT-0300 (BRT)';

        // Partes do horário (separadas por barras de espaço)
        var bparts = date.split(' ');

        // Verifica se o primeiro conjunto de caracteres são números
        for(var i = 0, charCode;
            (charCode = bparts[0].charCodeAt(i)) &&
                charCode >= 48 &&
                charCode <= 57;
            i ++);

        // Verifica se a data começa com um ano
        if(bparts.length === 1 && i >= 2) {

            // Partes da data (separadas por hífens)
            var hparts = date.split('-');

                // Ano
            var year = hparts[0],
                // Mês do ano
                month = parseFloat(hparts[1]),
                // Dia do mês
                day = parseFloat(hparts[2].substring(0, hparts[2].indexOf('T')));

            /* Parece que não há o dia da semana nessa data. */

            // Partes do horário
            var tparts = hparts[3].substring(1).split(':');

                // Horas
            var hours = parseFloat(tparts[0]),
                // Minutos
                min = tparts[1];

            // Adiciona o 0 na frente dos números se necessário.
            hours = hours <= 9 ? '0' + hours : hours;
            day = day <= 9 ? '0' + day : day;
            month = month <= 9 ? '0' + month : month;

            // Retorna o data como string.
            return day + '-' + month + '-' + year +
                   ' às ' + hours + ':' + min;

        }else{

            // Partes do horário (separados por dois pontos)
            var tparts = bparts[4].split(':');

                // Dia do mês
            var day = bparts[2],
                // Mês
                month =  monthies[bparts[1]],
                // +3 horas
                hours = (parseFloat(tparts[0]) + 3) % 24,
                // Minutos
                min = tparts[1],
                // Dia da semana
                week = weeks[bparts[0]],
                // Ano
                year = bparts[3];

            // Adiciona o 0 na frente dos números se necessário.
            hours = hours <= 9 ? '0' + hours : hours;
            day = day <= 9 ? '0' + day : day;
            month = month <= 9 ? '0' + month : month;

            // Retorna a data como string.
            return week + ', ' +
                   day + '-' + month + '-' + year +
                   ' às ' + hours + ':' + min;

        }

    });
})();

Example of use:

Date.toBrazilianFormat('2016-07-20T15:01:01-02:00'); // 20-07-2016 às 02:00

That date does not have the day of the week scheduled, so it was ignored.

1


I think there is no native method to convert this date into Javascript, but it is possible to do this manually.

Edit: After seeing the reply of @Ivanferrer I realized that there is already native method to do date conversion.

 // Raw da data
var rawdate = "Wed Jul 20 2016 14:01:01 GMT-0300 (BRT)",
 // Partes da data (separadas por barra de espaço)
 parts = rawdate.split(' '),
 // Partes do horário (separados por dois pontos)
 timeParts = parts[4].split(':');

// Dias da semana (de inglês abreviado para português)
var weeks = {
    "Sun": "Domingo",
    "Mon": "Segunda-feira",
    "Tur": "Ter\xe7a-feira",
    "Wed": "Quarta-feira",
    "Thu": "Quinta-feira",
    "Fri": "Sexta-feira",
    "Sat": "S\xe1bado"
};

// Número sequencial dos meses do ano
var monthies = {
    "Jan": 1,
    "Feb": 2,
    "Mar" : 3,
    "Apr" : 4,
    "May" : 5,
    "Jun" : 6,
    "Jul" : 7,
    "Aug" : 8,
    "Sep" : 9,
    "Oct" : 10,
    "Nov" : 11,
    "Dec" : 12
};

var date = {
    // Dia do mês
    day: parts[2],
    // Mês
    month: monthies[parts[1]],
    // Horário
    time: {
        // Horas
        hours: timeParts[0],
        // Minutos
        minutes: timeParts[1]
    },
    // Dia da semana
    week: weeks[parts[0]],
    // Ano
    year: parts[3]
};

// Raw português da data
var rawbrdate = date.week + ", " +
            /* Dia do mês */
            (date.day <= 9 ? '0' : '') + date.day +
            "-" +
            // Mês do ano
            (date.month <= 9 ? '0' : '') + date.month +
            "-" +
            // Ano
            date.year +
            /* Horário (+3h); corrigido. */
            " às " + ((parseFloat(date.time.hours) + 3) % 24) + ":" + date.time.minutes;

// Teste
console.log(rawbrdate);

Browser other questions tagged

You are not signed in. Login or sign up in order to post.