Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to display a Date object in a specific format using JavaScript?

I have a Date object and I'd like to display it in the below format:

var myDate = getDate();
// this format: "13 Jan 2012 11:00am";

How would that be possible?

Thanks,

like image 823
The Light Avatar asked Mar 02 '12 11:03

The Light


4 Answers

Use the build-in toLocaleString()

const date = new Date();

const formattedDate = date.toLocaleString("en-GB", {
  day: "numeric",
  month: "short",
  year: "numeric",
  hour: "numeric",
  minute: "2-digit"
});

console.log(formattedDate); // '18 Jan 2020, 18:20'
like image 144
zendka Avatar answered Sep 22 '22 23:09

zendka


EDIT: For modern apps (without IE support) please see the answer by @zendka https://stackoverflow.com/a/59802446/483616


There is a great JavaScript library that handles this very well, and only 5.5kb minified.

http://momentjs.com/

It looks something like this:

moment().format('MMMM Do YYYY, h:mm:ss a'); // February 25th 2013, 9:54:04 am
moment().subtract('days', 6).calendar(); // "last Tuesday at 9:53 AM"

You can also pass in dates as a String with a format, or a Date object.

var date = new Date();
moment(date); // same as calling moment() with no args

// Passing in a string date
moment("12-25-1995", "MM-DD-YYYY");

Also has great support for languages other than English, like Russian, Japanese, Arabic, Spanish and others.

Check out the docs.

like image 37
knownasilya Avatar answered Sep 22 '22 23:09

knownasilya


If you do not want to use any libraries:

<script type="text/javascript">

  var myDate = new Date();

  var month=new Array();
  month[0]="Jan";
  month[1]="Feb";
  month[2]="Mar";
  month[3]="Apr";
  month[4]="May";
  month[5]="Jun";
  month[6]="Jul";
  month[7]="Aug";
  month[8]="Sep";
  month[9]="Oct";
  month[10]="Nov";
  month[11]="Dec";
  var hours = myDate.getHours();
  var minutes = myDate.getMinutes();
  var ampm = hours >= 12 ? 'pm' : 'am';
  hours = hours % 12;
  hours = hours ? hours : 12;
  minutes = minutes < 10 ? '0'+minutes : minutes;
  var strTime = hours + ':' + minutes + ampm;
  // e.g. "13 Nov 2016 11:00pm";
  alert(myDate.getDate()+" "+month[myDate.getMonth()]+" "+myDate.getFullYear()+" "+strTime);
</script>
like image 38
George Avatar answered Sep 26 '22 23:09

George


There are many date formatting packages available for javascript, I've had great success with Steven Levithan's dateformat.

dateFormat(getDate(), "dd mmm yyyy hh:MMtt");

Edit: It also adds a format method to Date.prototype, if you enjoy that style:

getDate().format("dd mmm yyyy hh:MMtt");
like image 40
Linus Thiel Avatar answered Sep 26 '22 23:09

Linus Thiel