format date as long inside reactjs component

Want this format?

Wed, May 30, 2018`

Just declare

const DATE_OPTIONS = { weekday: 'short', year: 'numeric', month: 'short', day: 'numeric' };

And then in your React JS code

{(new Date()).toLocaleDateString('en-US', DATE_OPTIONS)}

toLocaleDateString() method returns a string with a language sensitive representation of the date portion of this date

Source and more options


Just do it in JS the usual way, before you start your return, and just template that in:

render: function() {
  var cts = this.props.message.createdAt,
      cdate = (new Date(cts)).toString();
  return (
    ...
    <span ...>{ cdate }</span>
    ...
  );
}

And there are quite a few ways you can do the string formatting, Date has a number of them built in (like toLocaleString or toUTCString), or you can use a dedicated formatter like moment.js


You could just run the regular JavaScript New Date(). However, I would strongly recommend using momentjs, as it seems to be more in line with what you are trying to do.

On the command line do:

npm install moment --save

Then in your code either var moment = require("moment"); or import moment from "moment"; depending on whether you are using ES6 or not.

After that, I would run code like so.

var timeAgo = moment(this.props.message.createdAt).fromNow()

<span className="date timeago" title={ timeAgo }> { timeAgo }</span>

Also, it may seem like a huge pain to install a package to do this, but moment is really nice and I would highly recommend it. The reason I recommended it is that it humanizes times. Like for instance, the fromNow() formatting makes it say 30 seconds ago, 4 days ago, or 3 months ago. It makes it sound like a person wrote it and it doesn't display tons of unnecessary info unless specified. I mean, most people don't want to know how many minutes and seconds ago it was if it was several hours ago. So, I recommended this library for those reasons. Feel free to use vanilla JS though if you prefer, I just find that moment is very nice for presentational purposes and let's me avoid having to write tons of math functions to display months, etc.