Reputation: 332
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
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
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
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:
Native date handling, for example Intl.DateTimeFormat
Specialized React component, for example react-moment
External package that can manipulate dates, such as moment
Which to use depends on your specific needs, but in general I would recommend those in the order they are given.
Upvotes: 14