How to format date in javascript?

51

I want to play the current date in an input, but in the "Brazilian" format dd / mm / yyyy.

My code:

var data = new Date();
dataFormatada = ?????
$("#Data").val(dataFormatada);
    
asked by anonymous 19.02.2014 / 18:54

8 answers

41

You can use a function to do it in order to simplify your work:

function dataAtualFormatada(){
    var data = new Date(),
        dia  = data.getDate().toString(),
        diaF = (dia.length == 1) ? '0'+dia : dia,
        mes  = (data.getMonth()+1).toString(), //+1 pois no getMonth Janeiro começa com zero.
        mesF = (mes.length == 1) ? '0'+mes : mes,
        anoF = data.getFullYear();
    return diaF+"/"+mesF+"/"+anoF;
}

For dd/mm/yyyy .

Example:

Today's date (code result above) in <input type=text id=Data> :

$('#Data').val(dataAtualFormatada);

It would result in the following in the value of the input:

  

02/19/2014

Update: the ES8 (ECMAScript 2017) has implemented the padStart , so the solution can be used in a simpler way:

function dataAtualFormatada(){
    var data = new Date(),
        dia  = data.getDate().toString().padStart(2, '0'),
        mes  = (data.getMonth()+1).toString().padStart(2, '0'), //+1 pois no getMonth Janeiro começa com zero.
        ano  = data.getFullYear();
    return dia+"/"+mes+"/"+ano;
}

Note:

This last solution will not work in Internet Explorer and in browsers that do not support ES8, for more information, see Compatibility table .

Polyfill

// https://github.com/uxitten/polyfill/blob/master/string.polyfill.js
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/padStart
if (!String.prototype.padStart) {
    String.prototype.padStart = function padStart(targetLength, padString) {
        targetLength = targetLength >> 0; //truncate if number, or convert non-number to 0;
        padString = String(typeof padString !== 'undefined' ? padString : ' ');
        if (this.length >= targetLength) {
            return String(this);
        } else {
            targetLength = targetLength - this.length;
            if (targetLength > padString.length) {
                padString += padString.repeat(targetLength / padString.length); //append to original to ensure we are longer than needed
            }
            return padString.slice(0, targetLength) + String(this);
        }
    };
}
    
19.02.2014 / 18:56
29

For those of you who do not want to reinvent the wheel, there's the moments.js library that handles this and many other operations involving dates in JavaScript. Among the functions of the moment is the formatting of dates in formats that can be assembled as strings. Example usage:

moment().format('MMMM Do YYYY, h:mm:ss a');
moment().format('dddd');
moment().format("MMM Do YY");
moment().format('YYYY [escaped] YYYY');
moment().format(); 

Note that using a library like this can be an exaggeration, if you only need to format dates in a single format.

    
19.02.2014 / 19:07
19

Use the native Javascript functions:

var data = new Date();
console.log(data.toLocaleDateString());

Reference: link

    
13.04.2015 / 07:25
17

If you are using jQuery UI, you can use an auxiliary function of datepicker :

$.datepicker.formatDate('dd/mm/yy', new Date())

(Note: I added this answer because I saw in your sample code the use of jQuery, although the question was about pure JavaScript.) It should also be noted that simple jQuery does not have datepicker , only jQuery UI) p>     

19.02.2014 / 19:02
6
  

("0" + data.getDate ()). substr (-2) // Ensures that there will be zero if < 9

In your case, it would be

var data = new Date();
var dataFormatada = ("0" + data.getDate()).substr(-2) + "/" 
    + ("0" + (data.getMonth() + 1)).substr(-2) + "/" + data.getFullYear();

Formatting date in Javascript can be done in just one line of code if you make a pad with "0" and substr . Most people never stopped to see that this is great. I discovered this a few years ago in the international OS, in a question.

Advantages of formatting with "0" and substr

  • Short and direct code
  • Fewer IFs
  • Less variables created
  • Weighs less than a library just to handle dates

Disadvantages

  • In situations that have to work with many different formats, use of specific libraries is simpler

Alternative to toISOString

A more readable alternative is toISOString, but it is not supported in IE8

var data = new Date();
console.log(data.toISOString().substr(0, 10).split('-').reverse().join('/'));

Documentation of Date.prototype.toISOString () in MDN, with Polyfill for unsupported browsers

    
19.02.2014 / 19:29
3

I used Paulo Roberto's answer as a base (I still had zero implementation in the months with one digit) and I did so:

var data = new Date();

var dia  = data.getDate();
if (dia< 10) {
    dia  = "0" + dia;
}

var mes  = data.getMonth() + 1;
if (mes < 10) {
    mes  = "0" + mes;
}

var ano  = data.getFullYear();
dataFormatada = dia + "/" + mes + "/" + ano;
$("#Data").val(dataFormatada);

Adding the zero in months with one digit.

    
19.02.2014 / 19:00
2

Based on this question I set up a small git with some auxiliary functions for these purposes .

Using the methods I have available can be done like this:

var d = new Date();
console.log(d.toDate('dd/mm/yyyy hh:ii:ss'));

console.log(d.toDate('mm/dd/yyyy hh:ii:ss'));

console.log(d.toDate('yyyy-mm-dd'));

console.log(d.toDate('yyyy-dd'));
<script src="https://rawgit.com/Lautert/helpers/master/javascript.helpers.js"></script>
    
07.04.2017 / 20:29
2

function formatDate(data, formato) {
  if (formato == 'pt-br') {
    return (data.substr(0, 10).split('-').reverse().join('/'));
  } else {
    return (data.substr(0, 10).split('/').reverse().join('-'));
  }
}

console.log(formatDate('23/04/2018'));
console.log(formatDate('2018-04-01', 'pt-br'));
    
02.05.2018 / 02:55