Javascript format date / time [duplicate]

Solution 1:

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/

Solution 2:

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>

Solution 3:

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.

Solution 4:

I don't think that can be done RELIABLY with built in methods on the native Date object. The toLocaleString method gets close, but if I am remembering correctly, it won't work correctly in IE < 10. If you are able to use a library for this task, MomentJS is a really amazing library; and it makes working with dates and times easy. Otherwise, I think you will have to write a basic function to give you the format that you are after.

function formatDate(date) {
    var year = date.getFullYear(),
        month = date.getMonth() + 1, // months are zero indexed
        day = date.getDate(),
        hour = date.getHours(),
        minute = date.getMinutes(),
        second = date.getSeconds(),
        hourFormatted = hour % 12 || 12, // hour returned in 24 hour format
        minuteFormatted = minute < 10 ? "0" + minute : minute,
        morning = hour < 12 ? "am" : "pm";

    return month + "/" + day + "/" + year + " " + hourFormatted + ":" +
            minuteFormatted + morning;
}

Solution 5:

You can do that:

function formatAMPM(date) { // This is to display 12 hour format like you asked
  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 strTime;
}

var myDate = new Date();
var displayDate = myDate.getMonth()+ '/' +myDate.getDate()+ '/' +myDate.getFullYear()+ ' ' +formatAMPM(myDate);
console.log(displayDate);

Fiddle