Format Date and Time Using react-intl FormattedDate and FormattedTime

Damon Bauer
InstructorDamon Bauer
Share this video with your friends

Social Share Links

Send Tweet
Published 7 years ago
Updated 4 years ago

Using the react-intl FormattedDate and FormattedTime components, we’ll render a JavaScript Date into both a date string and a time string in different language formats.

[00:01] In the bookDetail component, let's import formattedDate and formattedTime from React Intl. We'll use these components to render the date of the user's review. If we take a look at our sample book.json data, at the date for each person's review, you'll notice that it's one long number.

[00:25] This is an instance of a date represented in a Unix timestamp in milliseconds. Let's get rid of this date that we're displaying currently, and we'll add a formattedDate component.

[00:39] We'll provide a value prop, into that we'll create a new date and pass it review.date. So formattedDate takes a number of arguments, but we'll look at just a few. We'll set a year prop to numeric, I'll just go ahead and set the rest as well, so I'll say month='numeric', and day='numeric'.

[01:07] Notice that our dates are formatted in the correct locale format. To change that date format, let's change some of these props. We'll say month is no longer numeric, but we'll say long. Now we get the long month name in each of the different languages, but for this app I'll change everything to two digit.

[01:28] Now let's take a look at formattedTime. Recall that review.date was an instance of a date that included the time down to the millisecond, so using that information React Intl can render all of the date information that we provide it.

[01:49] I'll comment out formattedDate and I'll add formattedTime. Again, I'll provide a prop of value and pass a new date constructor with review.date as the value. By adding the same two-digit props for year, month, and day, we get a nice formatted date with the time added in each of the different languages.

egghead
egghead
~ 3 minutes ago

Member comments are a way for members to communicate, interact, and ask questions about a lesson.

The instructor or someone from the community might respond to your question Here are a few basic guidelines to commenting on egghead.io

Be on-Topic

Comments are for discussing a lesson. If you're having a general issue with the website functionality, please contact us at support@egghead.io.

Avoid meta-discussion

  • This was great!
  • This was horrible!
  • I didn't like this because it didn't match my skill level.
  • +1 It will likely be deleted as spam.

Code Problems?

Should be accompanied by code! Codesandbox or Stackblitz provide a way to share code and discuss it in context

Details and Context

Vague question? Vague answer. Any details and context you can provide will lure more interesting answers!

Markdown supported.
Become a member to join the discussionEnroll Today