Green Files

How to format date in JavaScript?

Day: 06/02/2022 - Time: 10:03:50

To put the current date in the dd/mm/yyyy format, you can use a function to do this, in order to simplify your work:

unction currentformateddata(){ var date = new Date(), day = data.getDate().toString(), dayF = (day.length == 1) ? '0'+day : day, month = (data.getMonth()+1).toString(), //+1 cause in getMonth January starts at zero. monthF = (month.length == 1) ? '0'+month : month, yearF = data.getFullYear(); return dayF+"/"+monthF+"/"+yearF; }

For dd/mm/yyyy

Example

Today (result of the code above) in a <input type=text id=Data>

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

It would result the following in the input value:

19/02/2022

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

function dataAtualFormatada(){ var date = new Date(), day = data.getDate().toString().padStart(2, '0'), month = (data.getMonth()+1).toString().padStart(2, '0'), //+1 cause in getMonth January starts at zero. year = data.getFullYear(); return day+"/"+month+"/"+year; }

Observation

This last solution will not work in Internet Explorer and in browsers that do not support ES8, for more information see the 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); } }; }

Reference:

https://pt.stackoverflow.com/questions/6526/como-formatar-data-no-javascript

GO UP
GO TO INDEX