Change the format of the current date with JQuery

0

I am currently showing the current date in this way:

    var date = new Date();

 var time = date.getFullYear() +"-"+date.getFullMonth() +"-"+date.getDate() +" "+ date.getHours() + ":" + date.getMinutes() + ":" + date.getSeconds();

But the new Date(); uses a format that I do not need:

2017-4-16 11:7:48

The format I need is:

2017-05-16 10:39:19 //año/mes/dia hh:mm:ss

How can I edit the method Date() to bring the date and time that I need?

    
asked by Javier Antonio Aguayo Aguilar 16.05.2017 в 16:43
source

3 answers

0

Try this

var d = new Date();
var strDate = d.getFullYear() + "-" + (d.getMonth()+1) + "-" + d.getDate() + " " + d.getHours() + ":" + d.getMinutes() + ":" + d.getSeconds();
    
answered by 16.05.2017 / 17:07
source
0

Based on the response of @ Gustavo Piris, try the following:

var strDate = d.getFullYear() + "-" + ((d.getMonth()+1)<10?'0'+(d.getMonth()+1):(d.getMonth()+1)) + "-" + (d.getDate()<10?'0'+d.getDate():d.getDate()) + " " + d.getHours() + ":" + (d.getMinutes()<10?'0'+d.getMinutes():d.getMinutes()) + ":" + (d.getSeconds()<10?'0'+d.getSeconds():d.getSeconds());
    
answered by 16.05.2017 в 17:58
0

It is best to create a function to format the values according to a mask "00" (z2) since this principle applies to both month and < em> hour, minutes and seconds .

Example:

function zero(n) {
 return (n>9 ? '' : '0') + n;
}
var date = new Date();

var time = date.getFullYear() +"-"+zero(date.getMonth()+1) +"-"+zero(date.getDate()) +" "+ zero(date.getHours()) + ":" + zero(date.getMinutes()) + ":" + zero(date.getSeconds());

console.log(time);

Original Reply:

You can create a new method for month and seconds .

Example:

Date.prototype.mes = function() {
  var m = this.getMonth() + 1; // getMonth() is zero-based
  return (m>9 ? '' : '0') + m;
};
Date.prototype.segundos = function() {
  var s = this.getSeconds();
  return (s>9 ? '' : '0') + s;
};

var date = new Date();
var dateFormat = date.getFullYear() + "-" + date.mes() + "-" + date.getDate() + " " + date.getHours() + ":" + date.getMinutes() + ":" + date.segundos();

console.log(dateFormat);

Source: get-string-in-yyyymmdd-format -from-js-date-object

    
answered by 16.05.2017 в 18:08