How to format date in Javascript by putting name of the month and day of the week

6

Hello. Home Have this date: 05/18/17 . Home And I need to convert it to this: May 18th (Thurs) Home May: May, (Thurs): Thursday Home Does anyone know how I do this using JavaScript and jQuery?

    
asked by anonymous 16.05.2017 / 20:08

3 answers

13

You must have saved the names of the days of the week and the days of the month. Having this is easy:

var meses = [
  "Janeiro",
  "Fevereiro",
  "Março",
  "Abril",
  "Maio",
  "Junho",
  "Julho",
  "Agosto",
  "Setembro",
  "Outubro",
  "Novembro",
  "Dezembro"
];
var dias = ["domingo", "Segunda", "Terça", "Quarta", "Quinta", "Sexta", "Sábado"]

function formatarData(str) {
  var partes = str.split('/').map(Number);
  var data = new Date('20' + partes[2], partes[1] - 1, partes[0]);
  var diaSemana = dias[data.getDay() % 7];
  var mes = meses[data.getMonth()];
  return [data.getDate(), mes.slice(0, 3).toLowerCase(), '(' + diaSemana.slice(0, 3) + ')'].join(' ');
}




var data = '18/05/17';
console.log(formatarData(data));

Another simple option is to use Locale , that is the browser defentions to show dates:

function formatarData(str) {
  var partes = str.split('/').map(Number);
  var data = new Date('20' + partes[2], partes[1] - 1, partes[0]);
  return data.toLocaleString([], { weekday: 'short', year: 'numeric', month: 'long', day: 'numeric' });
}




var data = '18/05/17';
console.log(formatarData(data));
    
16.05.2017 / 20:28
4

 var meses = [
      "Janeiro",
      "Fevereiro",
      "Março",
      "Abril",
      "Maio",
      "Junho",
      "Julho",
      "Agosto",
      "Setembro",
      "Outubro",
      "Novembro",
      "Dezembro"
    ];
    var days = ['Domingo','Segunda','Terça','Quarta','Quinta','Sexta','Sábado'];
    var data = '18/05/17';
    
    var formatData = data.replace(/(\d{2})(\/)(\d{2})/, "$3$2$1");  
    
    var newData = new Date(formatData);
    
    console.log(newData.getDate() + ' ' + meses[newData.getMonth()] + ' (' +  days[newData.getDay()]+ ')');

    
    
16.05.2017 / 21:19
-2

Javascript does not have this functionality natively. I suggest using a library for this, preferably Moment.js .

On the link page you have several examples of using your format function. At the bottom of the page you can change the language and see the same examples with results in Portuguese.

Do not forget to download the location file to Portuguese of Portugal / a> or Brazilian Portuguese .

    
16.05.2017 / 20:16