I'm wondering how to get the current date in this format :
"Year-Month-Day Hour:Minute:Second"
To Be like "2018-02-11 00:00:00"
How to achieve it?
I'm wondering how to get the current date in this format :
"Year-Month-Day Hour:Minute:Second"
To Be like "2018-02-11 00:00:00"
How to achieve it?
There's several way to get the output you're after. Unfortunately there is no built-in formatter which gets you the exact format you specify.
This mean you'd need a custom function, which also takes care of "padding" (putting zero's in front of the values under 10) and the awkward months being 0-based (0 = januari, 1 = februari and so on).
for example
function dateComponentPad(value) {
var format = String(value);
return format.length < 2 ? '0' + format : format;
}
function formatDate(date) {
var datePart = [ date.getFullYear(), date.getMonth() + 1, date.getDate() ].map(dateComponentPad);
var timePart = [ date.getHours(), date.getMinutes(), date.getSeconds() ].map(dateComponentPad);
return datePart.join('-') + ' ' + timePart.join(':');
}
console.log(formatDate(new Date()));
To explain what is going on, formatDate
expects a Date
object and from that it collects the date and time parts and maps the values to be padded with 0
if needed (ensuring a minimum string length of 2). Next the date and time parts are joined together using the desired notation.
If you're planning on using the date for anything other than displaying it to the user (e.g. process it on a server and/or store it in a database), you really want to look at the built-in Date.toISOString()
method, as that is the standard for date/time notation and it works across different timezones.
Visit https://momentjs.com/ best for date time format.
like moment().format('MMMM Do YYYY, h:mm:ss a'); // February 11th 2018, 1:02:39 pm