6

How can I get the current date in Javascript and format it this way "2015-03-25T12:00:00" ?

I would like to know if there is a function or method for this. I am not asking how to convert a string into another.

user1869935
  • 717
  • 2
  • 10
  • 23
  • 3
    `Date.toISOString()` https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString – pawel Feb 17 '16 at 19:59
  • 1
    You have to be careful with Date.toISOString() though...it's not supported by older browsers like IE8. – Ageonix Feb 17 '16 at 20:01
  • Also, toISOString is UTC by default, the OP seems to want sans timezone (so local). – RobG Feb 17 '16 at 23:38

4 Answers4

8

To be precise: .toISOString().slice(0, -5)

var d1 = new Date()
var str = d1.toISOString().slice(0, -5)
console.log(str);
user2167582
  • 5,986
  • 13
  • 64
  • 121
4

How can I get the current date in Javascript and format it this way "2015-03-25T12:00:00" ?

That seems to be an ISO 8601 format date without a timezone, which will be treated as a "local" time. There is a built—in toISOString method, but it always uses UTC.

So you can either write your own function (fairly trivial, see below) or use a library (really not required if you just want to format a date string).

I would like to know if there is a function or method for this.

Not a built–in function, no.

/* Return an ISO 8601 string without timezone
** @param {Date} d - date to create string for
** @returns {string} string formatted as ISO 8601 without timezone
*/
function toISOStringLocal(d) {
  function z(n){return (n<10?'0':'') + n}
  return d.getFullYear() + '-' + z(d.getMonth()+1) + '-' +
         z(d.getDate()) + 'T' + z(d.getHours()) + ':' +
         z(d.getMinutes()) + ':' + z(d.getSeconds())
          
}

document.write(toISOStringLocal(new Date()));
RobG
  • 142,382
  • 31
  • 172
  • 209
4

Use moment.js It will blow your mind. Add this script to you HTML

<script type="text/javascript" src="http://momentjs.com/downloads/moment-with-locales.js"></script>

And use this code:

var date=moment().format('YYYY-MM-DDTHH:mm:ss');
HFR1994
  • 536
  • 1
  • 5
  • 16
0

Try this function:

function(d) {

    var cad = "";

    try{
              cad =  d.getUTCFullYear() + "-" + pad(d.getMonth() + 1) + "-" + pad(d.getUTCDate()) + "T" + pad(d.getHours()) 
              + ":" + pad(d.getUTCMinutes()) + ":" + pad( d.getSeconds()) ;  

      return cad;
    }catch(e){
      return null;
    }  

  }
sev7nx
  • 21
  • 3