How to get selected date from React Native Date Picker

In this React Native source code example, the source code below illustrate how to get selected date from React Native Date Picker.

You can copy and adopt this source code example to your React Native project without reinventing the wheel.

This is a simple code snippet that you can build on or customize based on your project requirements.

If you are new to React Native and could not understand the code below you can move down to the comment section and drop a question.

import React, { Component } from 'react';
import { View, StyleSheet,DatePickerAndroid,Text} from 'react-native'

export default class App extends Component {

  async selectDate(){
    try {
      const {action, year, month, day} = await DatePickerAndroid.open({ date: new Date() });
      if (action !== DatePickerAndroid.dismissedAction) {
            console.log(year);
            console.log(month);
            console.log(day);
            }
          } catch ({code, message}) {
            console.warn('Cannot open date picker', message);
          }
      }
   render() {
      return (
         <View style={styles.container}>
           <Text
             style={{padding: 10,backgroundColor: 'rgb(94, 200, 100)'}}
             onPress={()=>this.selectDate()}>select date</Text>
         </View>
      )
   }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    alignItems: 'center',
    justifyContent: 'center',
    backgroundColor: '#ddd'
  },
})

If you have any questions or suggestions kindly use the comment box or you can contact us directly through our contact page below.

Add a Comment