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.
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.
To be precise: .toISOString().slice(0, -5)
var d1 = new Date()
var str = d1.toISOString().slice(0, -5)
console.log(str);
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()));
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');
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;
}
}