Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Formatting a Date String in React Native

I'm trying to format a Date String in React Native.

Ex: 2016-01-04 10:34:23

Following is the code I'm using.

var date = new Date("2016-01-04 10:34:23"); console.log(date); 

My problem is, when I'm emulating this on a iPhone 6S, it'll print Mon Jan 04 2016 10:34:23 GMT+0530 (IST) without any problem. But if I try with the iPhone 5S it prints nothing. And if you try to get the month by using a method like date.getMonth() it'll print "NaN".

Why is this? What is the workaround?

like image 272
Nimila Hiranya Avatar asked Jan 04 '16 11:01

Nimila Hiranya


People also ask

How do you date in react native?

To get the current date in react native has the Date() object it will return every time the current date and time when we use it. we have to just write new Date() and it returns the date object where we get a year, month, date, hours, minutes, and seconds.


2 Answers

The beauty of the React Native is that it supports lots of JS libraries like Moment.js. Using moment.js would be a better/easier way to handle date/time instead coding from scratch

just run this in the terminal (yarn add moment also works if using React's built-in package manager):

npm install moment --save 

And in your React Native js page:

import Moment from 'moment';  render(){     Moment.locale('en');     var dt = '2016-05-02T00:00:00';     return(<View> {Moment(dt).format('d MMM')} </View>) //basically you can do all sorts of the formatting and others } 

You may check the moment.js official docs here https://momentjs.com/docs/

like image 189
Joe Lu Avatar answered Sep 25 '22 02:09

Joe Lu


Easily accomplished using a package.

Others have mentioned Moment. Moment is great but very large for a simple use like this, and unfortunately not modular so you have to import the whole package to use any of it.

I recommend using date-fns (https://date-fns.org/) (https://github.com/date-fns/date-fns). It is light-weight and modular, so you can import only the functions that you need.

In your case:

Install it: npm install date-fns --save

In your component:

import { format } from "date-fns";  var date = new Date("2016-01-04 10:34:23");  var formattedDate = format(date, "MMMM do, yyyy H:mma");  console.log(formattedDate); 

Substitute the format string above "MMMM do, yyyy H:mma" with whatever format you require.

Update: v1 vs v2 format differences

v1 used Y for year and D for day, while v2 uses y and d. Format strings above have been updated for v2; the equivalent for v1 would be "MMMM Do, YYYY H:mma" (source: https://blog.date-fns.org/post/unicode-tokens-in-date-fns-v2-sreatyki91jg/). Thanks @Red

like image 41
Matt Rabe Avatar answered Sep 24 '22 02:09

Matt Rabe