klferreira
klferreira

Reputation: 332

Does React have an equivalent for Angular's DatePipe?

I've decided to start learning React this week, since there are so many jobs out there for this particular framework.

I come from an Angular background, and found myself wondering if there is an option in React that matches the purpose of Angular's DatePipe.

Upvotes: 15

Views: 13875

Answers (3)

Andre Mesquita
Andre Mesquita

Reputation: 918

I prefer use javascript's function "Intl.DateTimeFormat".

  const formatDate = (dateText) => {
    const date = new Date(dateText);
    return new Intl.DateTimeFormat("pt-PT", {
        day: "2-digit",
        month: "2-digit",
        year: "numeric"
      }).format(date);    
  };

  const formatTime = (dateText) => {
    const date = new Date(dateText);
    return new Intl.DateTimeFormat("pt-PT", {
        hour: "2-digit",
        minute: "2-digit",
        second: "2-digit"
      }).format(date);
  };

Upvotes: 0

Methodician
Methodician

Reputation: 2506

React doesn't include an equivalent to Angular's DatePipe, or any built-in Pipe type functionality. It's too bad because Pipes are awesome, though admittedly often abused by Angular novices.

I would also be hesitant to bring in another library/package/dependency for such a limited task, though Mitch's answer is still good.

Instead, I would embrace React's JavaScript-first mentality and simply create a function that takes a date and returns a string formatted how you'd like to display the date.

You could use JavaScript's in-built date parsing tools or parse an ISO Date as a string, like in the following function:

export const convertISOStringToMonthDay = date => {
  const tempDate = new Date(date).toString().split(' ');
  const formattedDate = `${tempDate[1]} ${+tempDate[2]}`;
  return formattedDate;
};

Upvotes: 2

Mitch Lillie
Mitch Lillie

Reputation: 2407

There is not a built-in feature of the React API that handles this for you, which is generally the case for all of the functionality covered by Angular pipes. Instead, you have really three options for date formatting in React:

Which to use depends on your specific needs, but in general I would recommend those in the order they are given.

Upvotes: 14

Related Questions