Reputation: 21
I am getting date data in this format from my API:
"2018-12-26T05:00:29"
however I need to display this in the application front end in a different format like this:
"Monday, Nov 26 at 10:00 am"
How can I achieve this in react-native?
Upvotes: 1
Views: 9289
Reputation: 486
While Moment.js can resolve this issue quickly, it's however a pretty big library to use for a single use case. I recommend using date-fns
instead. It's lite.
I come out of this thanks to https://github.com/date-fns/date-fns/issues/376#issuecomment-353871093.
Despite the solution, I did some perfection on Date Field Symbol. You may need to use dd
instead of DD
/ yyyy
instead of YYYY
for formatting days of the month / for formatting years.
Read the doc here: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md
Upvotes: 0
Reputation: 30360
Consider using a third-party library like momentjs for advanced date parsing and formatting. Using moment, you can format the date string as required via the following pattern:
// dddd for full week day, MMM for abreviated month, DD for date, etc
moment(inputDate).format("dddd, MMM DD at HH:mm a")
The momentjs library works well with react-native and can be easily installed by:
npm install moment --save
and imported into your project:
import moment from 'moment';
Here's a snippet demonstrating the pattern shown above:
var inputDate = "2018-12-26T05:00:29";
var outputDate = moment(inputDate).format("dddd, MMM DD at HH:mm a");
console.log(outputDate);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.23.0/moment.min.js"></script>
Upvotes: 5