How to Display Date and Time Picker in React Native?
Hi Guys,
In this tutorial, you will learn how to use community dateTimePicker in react native. this example will help you how to create community dateTimePicker in react native. if you have question about community dateTimePicker example in react native then I will give simple example with solution. you can understand a concept of how to add community dateTimePicker in react native. You just need to some step to done how to display date and time picker in react native.
Let's start following example:
Step 1: Download ProjectIn the first step run the following command to create a project.
expo init ExampleAppStep 2: Install and Setup
First of all you have to install React Native DateTimePicker package.
npm install @react-native-community/datetimepicker --saveStep 3: App.js
In this step, You will open the App.js file and put the code.
import React, { useState } from 'react'; import { Button, Platform, StyleSheet, Text, View } 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 [text, setText] = useState('Empty'); const onChang = (event, selectDate) => { const currentDate = selectDate || date; setShow(Platform.OS === 'ios'); setDate(currentDate); let tempDate = new Date(currentDate); let fDate = tempDate.getDate() + '/' + (tempDate.getMonth() + 1) + '/' + tempDate.getFullYear(); let fTime = "Hours: " + tempDate.getHours() + ' | Minutes: ' + tempDate.getMinutes(); setText(fDate + '\n' + fTime); } const showMode = (currentMode) => { setShow(true); setMode(currentMode); } return ( <View style={styles.container}> <Text style={styles.getDateTime}>{text}</Text> <View style={styles.buttonContainer}> <Button title='Date Picker' onPress={() => showMode('date')} /> </View> <View style={styles.buttonContainer}> <Button title='Time Picker' onPress={() => showMode('time')} /> </View> {show && <DateTimePicker testID='dateTimePicker' value={date} mode={mode} is24Hour={true} display='default' onChange={onChang} /> } </View> ); } const styles = StyleSheet.create({ container: { flex: 1, justifyContent: 'center', alignItems: 'center', backgroundColor: '#FFF', }, getDateTime: { fontWeight: 'bold', fontSize: 20, }, buttonContainer: { margin: 20, } }); export default App;Run Project
In the last step run your project using the below command.
expo start
You can QR code scan in Expo Go Application on mobile.
Output :
It will help you...