-1

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?

Sam
  • 163
  • 4
  • 10

2 Answers2

1

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.

Rogier Spieker
  • 4,087
  • 2
  • 22
  • 25
  • Thanks so much it worked , Can I ask you some more questions? – Sam Feb 11 '18 at 07:50
  • If they're related to this, sure. Otherwise you're probably better off asking new questions on SO ;-) – Rogier Spieker Feb 11 '18 at 08:08
  • it's related to the date , Do you know how to compare between two dates with the same format and then get the difference between them , I mean if the first is "2018-02-**11** 00:00:00**" and the current "2018-02-**12** 00:00:00" then it prints yesterday , ..etc – Sam Feb 11 '18 at 08:36
  • That kind of nice human readable output is nicely done by libraries such as momentjs, if you want to create it yourself you'll have to calculate the difference, which can be done by getting the time in milliseconds (`Date.getTime()`) from both dates and determine what the difference is and then present it the way you want (e.g. the number of milliseconds for dates exactly 24 hours apart is 86,400,000, which could either mean "yesterday" or "tomorrow" (depending on the order of dates in the subtraction). – Rogier Spieker Feb 11 '18 at 08:49
-1

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