React-native – how to use date and time pickers in react native

datetimepicker, react-native

I created a react native form and I want to add date and time Picker values to the form and the save them to backend. I have tried few libraries but failed.

Best Solution

You can use react-native-modal-datetime-picker

# using npm$ npm i react-native-modal-datetime-picker @react-native-community/datetimepicker# using yarn$ yarn add react-native-modal-datetime-picker @react-native-community/datetimepicker

Example

import React, { useState } from "react";import { Button, View } from "react-native";import DateTimePickerModal from "react-native-modal-datetime-picker";const Example = () => {  const [isDatePickerVisible, setDatePickerVisibility] = useState(false);  const showDatePicker = () => {    setDatePickerVisibility(true);  };  const hideDatePicker = () => {    setDatePickerVisibility(false);  };  const handleConfirm = date => {    console.warn("A date has been picked: ", date);    hideDatePicker();  };  return (    <View>      <Button title="Show Date Picker" onPress={showDatePicker} />      <DateTimePickerModal        isVisible={isDatePickerVisible}        mode="date"        onConfirm={handleConfirm}        onCancel={hideDatePicker}      />    </View>  );};export default Example;

SIMPLE EXAMPLE FOR YOUR PROBLEM

import React, { Component } from "react";import { View, Text, StyleSheet } from "react-native";import DateTimePicker from "react-native-modal-datetime-picker";export default class ExampleClass extends Component {  constructor(props) {    super(props);    this.state = {      isDatePickerVisible: false,      pickedDate: ""    };  }  //Date Picker handling methods  hideDatePicker = () => {    this.setState({ isDatePickerVisible: false });  };  handleDatePicked = date => {    const mdate = date.toString().split(" ");    this.setState({      pickedDate: mdate[1] + " " + mdate[2] + ", " + mdate[3]    });    this.hideDatePicker();  };  showDatePicker = () => {    this.setState({ isDatePickerVisible: true });  };  render() {    return (      <View style={styles.container}>        {/* Your View Here */}        <DateTimePicker          mode="date"          isVisible={this.state.isDatePickerVisible}          onConfirm={this.handleDatePicked}          onCancel={this.hideDatePicker}        />      </View>    );  }}const styles = StyleSheet.create({  container: {    flex: 1  }});