Convert time stamp to readable date


#1

Hi all

I have a simple plunker here - https://plnkr.co/edit/TVND2PPclgBwHyNvmh7Y?p=preview

I'm creating a new Date and alert

It outputs Tue Jan 16 2018 12:00:32 GMT+0000

How do I convert this to a readable date like Jan 2018


#2

Try adapting this code as required:

function formatDate(date) {
  var monthNames = [
    "January", "February", "March",
    "April", "May", "June", "July",
    "August", "September", "October",
    "November", "December"
  ];

  var day = date.getDate();
  var monthIndex = date.getMonth();
  var year = date.getFullYear();

  return day + ' ' + monthNames[monthIndex] + ' ' + year;
}

console.log(formatDate(new Date()));  // show current date-time in console

From: How to format a JavaScript date


#3

For the exact format you asked for, MMM YYYY, this is the shortest you can get away with in ES5:

function formatDate(date) {
  var dateString = date.toDateString();
  return dateString.slice(4, 7) + ' ' + date.getFullYear();
}

// usage:
console.log("It's now", formatDate(new Date()));

ES6 example:

const formatDate2 = date => `${date.toDateString().slice(4, 7)} ${date.getFullYear()}`

But if you need more complex formats and options, consider a library like Moment.js.


#4

If you are using PHP then try inserting the date like this because it would be done server side.

<script> alert( <?= date( DATE_RFC1123 ) ?> </script>

Unable to check because using a tablet.

http://php.net/manual/en/class.datetime.php#datetime.constants.types

// DateTime::RFC1123
// DATE_RFC1123
// RFC 1123 (example: Mon, 15 Aug 2005 15:52:01 +0000)


closed #5

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.