78
I want to play the current date on one input
, but in the "Brazilian" dd/mm/yyyy
.
My code:
var data = new Date();
dataFormatada = ?????
$("#Data").val(dataFormatada);
78
I want to play the current date on one input
, but in the "Brazilian" dd/mm/yyyy
.
My code:
var data = new Date();
dataFormatada = ?????
$("#Data").val(dataFormatada);
76
You can use a function to do so 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;
}
To dd/mm/yyyy
.
Today (result of the above code) in a <input type=text id=Data>
:
$('#Data').val(dataAtualFormatada);
It would result in the following, in the value of the input:
19/02/2014
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;
}
This last solution will not work in Internet Explorer and in browsers that do not have ES8 support, for more information see the compatibility table.
// 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);
}
};
}
The only problem with this approach is that if the day or month has a single digit, it has zero left.
that’s true, thank you for remembering @mgibsonbr
Now you no longer have this problem @mgibsonbr
But the day!?!?
opsss @utluiz pera aí - pronto. haha
I dare to point out the case of the years before 1000
? :P (well that Javascript could have an easy way to do padding with zeroes on the left...)
ah @mgibsonbr there right ? auhauhau but I agree with you guy, should have ... this javascript still kills me from the heart..
@mgibsonbr I’ve never seen zero-padding in years (on strings for the purpose of being read by humans)
If you do this $("#Data"). val(dateOutdate); does it work? or do I have to fill in the variable before like this: dateOutdate = dateOutdate(); ?
Yes @Joaopaulo, works only with $("#Data").val(dataAtualFormatada);
. I edited my question by putting this exact example for better understanding.
@Pauloroberto wow, did not know this functionality of val
(pass a function to update the current value), good to know that it exists! And as for the zero-padding of the years, I don’t know how it should be (with or without), but there aren’t many practical applications that mess with historical data and for which it would make a lot of difference, so whatever... I put the comment more as a joke.
53
Use native Javascript functions:
var data = new Date();
console.log(data.toLocaleDateString());
Reference: http://www.w3schools.com/jsref/jsref_obj_date.asp
very practical and also native, thanks!
this is undoubtedly the best answer and should have been chosen as correct by adopting a native language solution without the need to implement new functions and third party libraries.
Best answer!
Resolve, but if it’s on the client side it might not take the DD/MM/YYYY formatting because of the locale. To stay with this pattern is good to pass the locale data.toLocaleDateString("pt-BR")
. But it was definitely the best answer :D
Man, just sensational!!
42
For those who don’t want to reinvent the wheel, there’s the library Moments.js, that handles this and several other operations involving Javascript dates. Among the functions of Moment is the formatting of dates in formats that can be mounted as strings. Example of use:
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 your need is only to format dates, in a single format.
It is rare that you see me post library suggestions here, I really like pure code. But this I thought was worth it.
Interesting, but I found it kind of strange to understand, I don’t know.
I made that same recommendation in SOE these days. The way of doing things reminds a lot of the Simpledateformat of Java and Format Strings of . NET.
A note for those who want to use Moment.js in the future: Moment was built for the Previous era of the Javascript Ecosystem. The Modern web looks Much Different These days., present in the documentation of Moment.js. So if you’re going to add this dependency now in the project, think twice and try to do without :)
20
If you are using jQuery UI, you can use an auxiliary function from datepicker
:
$.datepicker.formatDate('dd/mm/yy', new Date())
(Note: I added this answer because I saw in your example 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 the jQuery UI)
Good option. Only need 'yy' to show 2014?
@Joaopaulo Yes. I do not know if there is even option to format year with two digits...
I managed to show year with two digits using 'dd/mm/y'. It worked, and apparently did not lead to major problems, at least in my code
9
("0" + date.getDate()). substr(-2) // Ensures 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 only one line of code if you make a pad with "0" and substr
. Most people never stop to see that this is genius. I discovered this a few years ago in the international OS, in a question.
substr
A more readable alternative is toISOString, but it has no IE8 support
var data = new Date();
console.log(data.toISOString().substr(0, 10).split('-').reverse().join('/'));
Date.prototype.toISOString() documentation on MDN,com Polyfill for unsupported browsers
And the disadvantages? p
@Pauloroberto Not trivial to read. And breaks the limit of columns that some like to have in each row. Just same style.
This is a snippet. Either you understand the concept of replacing and remembering right away, or you copy and paste a code ready. As for being trivial to read, well, that’s pure javascript. It’s not an entire library that applies regex to format a date, so I don’t see much problem with not being readable. In fact, notice that it should work up to IE5
Actually I find it very readable.
Yeah.. I withdraw the "not trivial to read". I’m just not as familiar with JS and saw a big line too :)
5
I used Paulo Roberto’s answer as a basis (I had not yet implemented from scratch in the months with a 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 zero in months with a digit.
but I went faster and edited and put the zero in the months, haha. + 1 for you because it’s correct. and I found interesting your (mes < 10)
I used the length of the month transformed to string =x
for if’s that contain only one line of code to run you don’t need braces that would be {
and }
And really the day also needs this if! When the OS leaves, I will mark yours as answered question. Thanks @Paulo Roberto! Yes I know about braces, but I like to use them because for me it is clearer the code.
You are welcome, my dear @Joaopaulo :)
5
Complementing the other answers...
You mention "Brazilian format" and then "dd/mm/yyyy". Although they are "the same thing" (since it is the most common format in Brazil), there are some considerations regarding the methods used in the other answers. Let’s see:
toLocaleDateString
One of the answers suggests using toLocaleDateString()
no parameters. This may or may not work, since this method, when called without parameters, uses the locale which is configured in the environment where the code runs (which may be the configuration of the browser, or, in the case of Node, the operating system configuration/shell).
For example, the code below:
var date = new Date();
console.log(date.toLocaleDateString());
I ran this code today (February 9, 2021, 9:00 at Brasília Time) on the Node on an Ubuntu machine configured in English. Running the code above, the result was 2/9/2021
(the irritating American format, with the month before the day, and without the zeros on the left for values less than 10).
So to make sure that the Brazilian format will be used, you have to inform the locale (in the case, pt-BR
, which is equivalent to Brazilian Portuguese):
date.toLocaleDateString('pt-BR')
Then the correct format will be used, and the output will be 09/02/2021
.
On Node, it is also possible to set at the beginning of the script (Obs: does not work on Windows):
process.env.LANG="pt-BR.utf8";
// restante do código
In that case, call toLocaleDateString()
no parameters will use the locale pt-BR
and the Brazilian format will be used. But this also changes the configuration of all functions that use the default locale of the environment (such as toLocaleString()
for numbers, among others), and this may not always be the desired. So if you already know which locale want to use, better pass it directly as parameter, without needing to change a setting that can affect other parts.
But there is one detail: whether the locale not installed, this does not guarantee that the correct format will be used. For example, the Node < 13 did not come with the locales installed, then even using pt-BR
, was made the fallback for the American format. And there is also the possibility - rarer, but still possible - of the format associated with locale change.
And just for the record, an alternative that wasn’t covered in the other answers: it’s possible to use Intl.DateTimeFormat
:
var formatter = new Intl.DateTimeFormat('pt-BR');
var date = new Date();
console.log(formatter.format(date));
It works in a similar way to toLocaleDateString()
, however according to the documentation, Intl.DateTimeFormat
has better performance when you need to format many dates (just create one and use the method format
).
Another possibility, not to depend on locale pt-BR
be installed in the environment where the code runs, is to format the date manually.
Several responses use the getters to get the values of the day, month and year, and then build the string, and one in particular uses toISOString
to obtain these same values. This is a case where one should beware, for toISOString
returns the date in UTC, as long as the getters return values based on the environment Timezone (browser/OS).
See an example that makes a difference (Attention, you should run the code below in a browser configured in Brasília Time, otherwise the results may be different):
function pad(valor) { // completa com zero à esquerda, se necessário
return valor.toString().padStart(2, '0');
}
// 9 de de fevereiro de 2021, às 23:00
var date = new Date(2021, 1, 9, 23, 0);
// usando toLocaleDateString
console.log(date.toLocaleDateString('pt-BR')); // 09/02/2021
// usando os getters
console.log(`${pad(date.getDate())}/${pad(date.getMonth() + 1)}/${pad(date.getFullYear())}`); // 09/02/2021
// usando o código da outra resposta (/a/417433/112052)
console.log(date.toISOString().match(/^[0-9]{4}\-[0-9]{2}\-[0-9]{2}/)[0].split('-').reverse().join('/')); // 10/02/2021
If your browser is set to Brasilia Time (Chrome and Firefox take from the operating system, the rest I’m not sure), then you will notice that the first 2 returned the correct date (09/02/2021
), while toISOString
returned a day later (10/02/2021
).
This is because toISOString
returns the date and time in UTC, while toLocaleDateString
and the getters return the values using the browser’s Timezone. And how February 9, 2021, 23:00 pm at Brasília Time amounts to 10 February 2021, 02:00 in UTC, we have that difference. So this is a point of attention, if you decide to use toISOString
(remembering that in different time zones, the dates/times when this occurs may vary - in some cases, it may even return a day earlier, for example).
Besides, once you have the values (either in UTC or in the browser Timezone), the other answers already give you many options to format them, and on this specific point there is not much to add.
4
new Date(myDateString).toLocaleDateString('pt-br');
Example:
console.log(new Date('2021/01/07').toLocaleDateString('pt-br'));
"07/01/2021"
Try this
4
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'));
The question asks how to format an object Date
, then I believe that your answer is missing the part where you convert such an object to string, since its function only works to string.
var dataAtual = new Date(); console.log(formatDate(dateAtual.toISOString(), 'en'));
4
Based on this question I have assembled a small git with some auxiliary functions for these purposes.
Using the methods I’ve provided you can do so :
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>
https://rawgit.com/Lautert/helpers/master/javascript.helpers.js is no longer available
@durtto here walks this online, are sure it is not access lock?
1
You can format using template string
:
const formatar = (data) => {
const ano = data.getFullYear();
const mes = (`00${data.getMonth() + 1}`).slice(-2);
const dia = (`00${data.getDate()}`).slice(-2);
return `${dia}/${mes}/${ano}`;
};
// Teste da função
console.log(formatar(new Date()));
Template literals are string literals that allow embedded expressions. You can use multi-line string and string interpolation with them. They were called "template strings" in versions prior to the ES2015 specification.
Syntax
`corpo de texto` `texto linha 1 texto linha 2` `texto string ${expression} texto string` tag `texto string ${expression} texto string`
0
console.log( (new Date()).toISOString().match(/^[0-9]{4}\-[0-9]{2}\-[0-9]{2}/)[0].split('-').reverse().join('/') )
Browser other questions tagged javascript date
You are not signed in. Login or sign up in order to post.
Last night I was thinking about it! It would be very interesting if there was an approach similar to the
SimpleDateFormat
java ordate
of PHP.– utluiz
Regex mais pratico http://stackoverflow.com/a/15504877/2777092 or use metodo http://www.w3schools.com/js/js_date_methods.asp
– KingRider