Javascript format date / time

For the date part:(month is 0-indexed while days are 1-indexed)

var date = new Date('2014-8-20');
console.log((date.getMonth()+1) + '/' + date.getDate() + '/' +  date.getFullYear());

for the time you'll want to create a function to test different situations and convert.


Please do not reinvent the wheel. There are many open-source and COTS solutions that already exist to solve this problem.

Please take a look at the following JavaScript libraries:

  • Luxon: [CDN] | [Source] | [Minified]
  • Moment.js: [CDN] | [Source] | [Minified]
  • Datejs: [CDN] | [Source] | [Alpha1.zip (1.6MB)]

Demo

Update: I wrote a one-liner using Moment.js Luxon below.

const { DateTime } = luxon;

const value = DateTime
  .fromFormat("2014-08-20 15:30:00", "yyyy-MM-dd HH:mm:ss")
  .toFormat('MM/dd/yyyy h:mm a');

console.log(value); // 08/20/2014 3:30 PM
<script src="https://cdnjs.cloudflare.com/ajax/libs/luxon/1.26.0/luxon.min.js"></script>

Here is the original version using Moment. Since Luxon is the successor to Moment, I have included this as an alternative.

const value = moment('2014-08-20 15:30:00').format('MM/DD/YYYY h:mm a');

console.log(value); // 08/20/2014 3:30 pm
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>

Yes, you can use the native javascript Date() object and its methods.

For instance you can create a function like:

function formatDate(date) {
  var hours = date.getHours();
  var minutes = date.getMinutes();
  var ampm = hours >= 12 ? 'pm' : 'am';
  hours = hours % 12;
  hours = hours ? hours : 12; // the hour '0' should be '12'
  minutes = minutes < 10 ? '0'+minutes : minutes;
  var strTime = hours + ':' + minutes + ' ' + ampm;
  return (date.getMonth()+1) + "/" + date.getDate() + "/" + date.getFullYear() + "  " + strTime;
}

var d = new Date();
var e = formatDate(d);

alert(e);

And display also the am / pm and the correct time.

Remember to use getFullYear() method and not getYear() because it has been deprecated.

DEMO http://jsfiddle.net/a_incarnati/kqo10jLb/4/