Formatting a Date String in React Native
Asked Answered
M

10

90

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?

Michey answered 4/1, 2016 at 11:41 Comment(0)
D
186

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/

Duckworth answered 8/3, 2017 at 3:23 Comment(4)
Moment is great but very large for common usages, and unfortunately not modular so you have to import the whole package to use it. Consider using date-fns (date-fns.org) instead. It is modular, so you can just import { format } from 'date-fns' and format(new Date(), 'MMMM Do, YYYY H:mma'), etc.Albumose
@MattRabe you should have added this as an answer. Another difference I found is Moment seems to be applicable only in HTML and date-fns can be used everywhere in a component.Shelter
Keep in mind the lowercase 'd' is Day of Week not Day of Month 'D'.Delisadelisle
moment no longer supported momentjs.com/docsAmund
A
62

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

Albumose answered 24/1, 2020 at 0:41 Comment(1)
Indeed. Also can't believe this was 4 years ago. Although with this project Moment became quite useful, with timezone utilities etc.Michey
B
32

There is no need to include a bulky library such as Moment.js to fix such a simple issue.

The issue you are facing is not with formatting, but with parsing.

As John Shammas mentions in another answer, the Date constructor (and Date.parse) are picky about the input. Your 2016-01-04 10:34:23 may work in one JavaScript implementation, but not necessarily in the other.

According to the specification of ECMAScript 5.1, Date.parse supports (a simplification of) ISO 8601. That's good news, because your date is already very ISO 8601-like.

All you have to do is change the input format just a little. Swap the space for a T: 2016-01-04T10:34:23; and optionally add a time zone (2016-01-04T10:34:23+01:00), otherwise UTC is assumed.

Byington answered 19/7, 2017 at 14:30 Comment(0)
A
9

Write below function to get date in string, convert and return in string format.

getParsedDate(strDate){
    var strSplitDate = String(strDate).split(' ');
    var date = new Date(strSplitDate[0]);
    // alert(date);
    var dd = date.getDate();
    var mm = date.getMonth() + 1; //January is 0!

    var yyyy = date.getFullYear();
    if (dd < 10) {
        dd = '0' + dd;
    }
    if (mm < 10) {
        mm = '0' + mm;
    }
    date =  dd + "-" + mm + "-" + yyyy;
    return date.toString();
}

Print it where you required: Date : {this.getParsedDate(stringDate)}

Archean answered 5/8, 2019 at 13:5 Comment(0)
A
4

A lightweight alternative for momentjs is dayjs

You can install it by using either yarn or npm

yarn add dayjs
# or
npm install --save dayjs
import dayjs from "dayjs";

dayjs("2016-01-04 10:34:23").format("d MMM");
// 4 Jan
Ademption answered 26/9, 2022 at 13:25 Comment(0)
B
3

The Date constructor is very picky about what it allows. The string you pass in must be supported by Date.parse(), and if it is unsupported, it will return NaN. Different versions of JavaScript do support different formats, if those formats deviate from the official ISO documentation.

See the examples here for what is supported: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/parse

Bobbie answered 4/1, 2016 at 18:6 Comment(0)
R
3
function getParsedDate(date){
  date = String(date).split(' ');
  var days = String(date[0]).split('-');
  var hours = String(date[1]).split(':');
  return [parseInt(days[0]), parseInt(days[1])-1, parseInt(days[2]), parseInt(hours[0]), parseInt(hours[1]), parseInt(hours[2])];
}
var date = new Date(...getParsedDate('2016-01-04 10:34:23'));
console.log(date);

Because of the variances in parsing of date strings, it is recommended to always manually parse strings as results are inconsistent, especially across different ECMAScript implementations where strings like "2015-10-12 12:00:00" may be parsed to as NaN, UTC or local timezone.

... as described in the resource:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/parse

Reahard answered 20/10, 2017 at 8:22 Comment(0)
P
2

Here's my solution.

/**
 * Instantiates a date Date object, used because doing the following doesn't
 * work in React-Native but does work in the browser.
 * ```
 * // Replace this with
 * var date = new Date('2020-08-11 21:23:00')
 * // with
 * var date = safeNewDate('2020-08-11 21:23:00')
 * ```
 * @param {string} localDateTimeStr
 * @returns {Date}
 */
export const safeNewDate = function(localDateTimeStr) {

  var match = localDateTimeStr.match(
    /(\d{4})-(\d{2})-(\d{2})[\sT](\d{2}):(\d{2}):(\d{2})(.(\d+))?/,
  )
  if (!match) throw new Error('Invalid format.')

  var [, year, month, date, hours, minutes, seconds, , millseconds] = match

  return new Date(
    year,
    Number(month) - 1,
    date,
    hours,
    minutes,
    seconds,
    millseconds || 0,
  )
}
Piranha answered 11/8, 2021 at 11:28 Comment(0)
A
0

I had the same problem. I handled the following:

  const modifiedString = string => {
     const splitString = string.split('...');
     var newStr = '';
     for (var i = 0; i < splitString.length; i++) {
        if (splitString[i] !== '' && splitString[i] !== ' '){
        newStr = (
           <Text style={{ flexDirection: 'row', width: 200 }}>
              <Text>{newStr}</Text>
              <Text>{splitString[i]}</Text>
              <SuperFill data={res[i]} check={checkX} />
           </Text>
           );
        }
     }
   return newStr;
 };

My SuperFill is a TextInput

Aventine answered 28/4, 2021 at 10:21 Comment(0)
G
0

Use Pure JavaScript:

const date = new Date(); // Or your date object
const formattedDate = date.toLocaleDateString('en-GB', {
  day: '2-digit',
  month: '2-digit',
  year: 'numeric',
});

console.log(formattedDate)
Globate answered 15/7, 2024 at 2:38 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.