DEV Community

Cover image for ReactNative datetimepicker to pick both date and time in Android
Karthikayan
Karthikayan

Posted on

ReactNative datetimepicker to pick both date and time in Android

The @react-native-community/datetimepicker provides the feature to pick date and time using the native components of Android and iOS.

For iOS, there seems to be no problem in picking up both date and time at the same time ('datetime' mode). But for Android, it is not possible out of the box. So, I thought of writing this.

I'll start from the existing usage instructions for the datetimepicker

import React, {useState} from 'react';
import {View, Button, Platform} from 'react-native';
import DateTimePicker from '@react-native-community/datetimepicker';

const App = () => {
  const [date, setDate] = useState(new Date());
  const [mode, setMode] = useState('date');
  const [show, setShow] = useState(false);

  const onChange = (event, selectedDate) => {
    const currentDate = selectedDate || date;

    setDate(currentDate);
    setShow(Platform.OS === 'ios' ? true : false);
  };

  const showMode = currentMode => {
    setShow(true);
    setMode(currentMode);
  };

  const showDatepicker = () => {
    showMode('date');
  };

  const showTimepicker = () => {
    showMode('time');
  };

  return (
    <View>
      <View>
        <Button onPress={showDatepicker} title="Show date picker!" />
      </View>
      <View>
        <Button onPress={showTimepicker} title="Show time picker!" />
      </View>
      {show && (
        <DateTimePicker
          testID="dateTimePicker"
          timeZoneOffsetInMinutes={0}
          value={date}
          mode={mode}
          is24Hour={true}
          display="default"
          onChange={onChange}
        />
      )}
    </View>
  );
};

export default App;

Let's use a clickable Text component showing datetime instead of the buttons. We don't need showTimePicker() anymore and thus can be removed.

        <TouchableOpacity onPress={showDatePicker}>
          <Text>{date}</Text>
        </TouchableOpacity>

Now, we need to modify the onChange() method to show up both date and time picker. Before that we need a time state similar to date state.

  const [time, setTime] = useState(new Date());
  //...
  const onChange = (event, selectedValue) => {
    setShow(Platform.OS === 'ios');
    if (mode == 'date') {
      const currentDate = selectedValue || new Date();
      setDate(currentDate);
      setMode('time');
      setShow(Platform.OS !== 'ios'); // to show the picker again in time mode
    } else {
      const selectedTime = selectedValue || new Date();
      setTime(selectedTime);
      setShow(Platform.OS === 'ios');
      setMode('date');
    }
  };

Now, we have date and time picker working and updating the respective state values. We just need to merge and format the date and time state.

        <TouchableOpacity onPress={showDatePicker}>
          <Text style={styles.title}>{formatDate(date, time)}</Text>
        </TouchableOpacity>

//..

const formatDate = (date, time) => {
  return `${date.getDate()}/${date.getMonth() +
    1}/${date.getFullYear()} ${time.getHours()}:${time.getMinutes()}`;
};

Checkout my git repo for the source,

GitHub logo ParkourKarthik / datetimepicker-demo

Demo app for using reactnative datetimepicker for picking both date and time.

P.S: This is my first ever post. I'd love to hear back ❤️. Also, I've considered only Android and I'm not sure if the code could impact iOS app if both native apps are used with a single source.

Top comments (5)

Collapse
 
gtbhopale2412 profile image
gtbhopale2412

Hi @Karthikayan
Thanks for the example. I am showing the selected date/time using formatDate(date, time) method. But when i click on the Cancel button of date picker it gives me an error like : TypeError:undefined is not an object (evaluating 'date.getDate')

My Versions:
datetimepicker: 2.4.0
react-native:0.62.13
Thanks in advance for the help.

Collapse
 
22ivan22 profile image
22ivan22

Hi gtbhopale2412,
you probably have state declared like date: ' '. You should put date: new Date() and time: new Date() also

Collapse
 
isaachatilima profile image
Isaac Hatilima

Hi @parkourkarthik, the onChange prop closes the time modal after choosing the hour. I have to open it again to choose the minutes.

Collapse
 
kamalhossain profile image
Kamal Hossain

thanks for this interesting stuff, keep posting stuff with great details.

Collapse
 
manuelwenner profile image
Manuel Wenner

Hi @Karthikayan, thanks for this solution. It works out perfect and is exactly what i needed.