Ad

Format An Array With Date Objects And Show Them In A Dropdown

- 1 answer

I have an API call which returns an array of objects. Inside these objects, I have a date / timestamp which is formatted as ISO (correct me if I'm wrong).

The code below is right after my render() method:

const pickerItems = this.props.currentData.trips.map(trip => {
    return { 
        label: trip.start.timestamp, 
        value: trip.tripId 
    };
  });

  console.log(pickerItems);

The console log returns the following:

Array [
  Object {
    "label": "2019-05-24T10:12:01.123Z",
    "value": "1C8EB4E0888640ED9211CB8C563542D0",
  },
Object {
    "label": "2019-05-24T10:12:01.123Z",
    "value": "1C8EB4E0888640ED9211CB8C563542D0",
  },
]

My Dropdown component:

<RNPickerSelect items={pickerItems} />

How could I do the below task in most simple & efficient way?

- Make a dropdown list where all the label (which is sent down as items) is the current date formatted as: 2019-05-24 followed by the exact time.

Thanks beforehand, Erik

Ad

Answer

When you are mapping your array, you should change ISO date to normal date and use it like the one below:

const pickerItems = this.props.currentData.trips.map(trip => {
      const someDay= new Date(trip.start.timestamp)
        return { 
            label: `${someDay.geyFullYear()}-{someDay.getMonth + 1}-{someDay.getDate() ${someDay.getHours()}:${someDay.getMinutes()}}`, 
            value: trip.tripId 
        };
      });

      console.log(pickerItems);
Ad
source: stackoverflow.com
Ad