How to show date without time with Date()

Asked

Viewed 4,078 times

4

I’m mounting a date to be displayed in an input, this will be today’s date less a day, but I need only the date and is showing me Date and Time, how can I do?

What I got so far is this:

var Hoje = new Date();
Hoje.setDate(Hoje.getDate() - 1);
var Today = Hoje.toLocaleString();
var Today = Today.replace(new RegExp("/", 'g'),"-" );
editors['DataIndice'].setValue(Today);

2 answers

6

I would do so:

 var data = new Date().toLocaleString().substr(0, 10)

 console.log(data)
But it’s important to report that when I used this, it didn’t work very well in Internet Explorer (as expected).

In any case, I always recommend using the library Momentjs

Example:

var data = moment().format('DD/MM/YYYY');



console.log(data);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.19.2/moment.min.js"></script>

To lessen a day in the moment, you can use the method add

var date = moment().add(-1, 'days').format('DD/MM/YYYY');


console.log(date);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.19.2/moment.min.js"></script>

5


var Hoje = new Date();
Hoje.setDate(Hoje.getDate() - 1);
//string apenas de data em um formato determinado pelo browser
var Today = Hoje.toDateString();
// string apenas de data no formato localizado do seu sistema
var Today2 = Hoje.toLocaleDateString();

var dataTracinho = Today2.replace(new RegExp("/","g"), "-"); 

console.log (Today);
console.log (Today2);
console.log (dataTracinho);

support:

I tested with the 6 main browsers, Chome, IE, Edge Firefox, Opera

5principais

and Safari

safari

For all browsers you can use Datejs see one clicking here

<script type="text/javascript" src="date.js"></script>
<script language="javascript">
   var d1 = Date.parse('today');;
   document.write(d1.toString('dd-MM-yyyy'));
</script>
  • Cara, bacana! + 1... I just wanted to know if it has support for all browsers. It would be interesting to put this information.

Browser other questions tagged

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