Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript format date / time [duplicate]

I need to change a date/time from 2014-08-20 15:30:00 to look like 08/20/2014 3:30 pm

Can this be done using javascript's Date object?

like image 515
user2994560 Avatar asked Aug 12 '14 23:08

user2994560


2 Answers

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/

like image 137
Alessandro Incarnati Avatar answered Oct 12 '22 18:10

Alessandro Incarnati


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>
like image 40
Mr. Polywhirl Avatar answered Oct 12 '22 16:10

Mr. Polywhirl