The JavaScript’s inbuilt function Date().getDate() gives us the facility to retrieve Get Current Date With Month And Year in both android and iOS applications on button click. So in this tutorial we would going to get current date using Date().getDate() function, retrieve current month using Date().getMonth() function and current year using Date().getFullYear() function and display inside react native app using Alert dialog.
Contents in this project Get Current Date With Month And Year in React Native App:
1. Import StyleSheet, View, Alert and Button component in your project.
1
2
3
|
import React, { Component } from ‘react’;
import { StyleSheet, View, Alert, Button } from ‘react-native’;
|
2. Create a function named as ShowCurrentDate(). Now we would get current date, month and year using Date() function and store each value into separate Var variable. Finally we would show all values on application screen with – (Dash) into Alert dialog.
Note : We need to +1 to month to show the correct month because by default in react native January starts from 0(Zero).
1
2
3
4
5
6
7
8
9
|
ShowCurrentDate=()=>{
var date = new Date().getDate();
var month = new Date().getMonth() + 1;
var year = new Date().getFullYear();
Alert.alert(date + ‘-‘ + month + ‘-‘ + year);
}
|
3. Create a Parent View in render’s return block and add a Button component inside it. Now we would set onPress event on button and call the ShowCurrentDate() function on button onPress.
1
2
3
4
5
6
7
8
9
10
11
12
|
render() {
return (
<View style={styles.MainContainer}>
<Button title=“Show Current Date” onPress={this.ShowCurrentDate} />
</View>
);
}
|
4. Create Style for View.
1
2
3
4
5
6
7
8
9
10
11
12
|
const styles = StyleSheet.create(
{
MainContainer: {
justifyContent: ‘center’,
flex: 1,
backgroundColor: ‘#F5FCFF’,
margin: 10
}
});
|
5. Complete source code for App.js File :
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
|
import React, { Component } from ‘react’;
import { StyleSheet, View, Alert, Button } from ‘react-native’;
export default class MyProject extends Component {
ShowCurrentDate=()=>{
var date = new Date().getDate();
var month = new Date().getMonth() + 1;
var year = new Date().getFullYear();
Alert.alert(date + ‘-‘ + month + ‘-‘ + year);
}
render() {
return (
<View style={styles.MainContainer}>
<Button title=“Show Current Date” onPress={this.ShowCurrentDate} />
</View>
);
}
}
const styles = StyleSheet.create(
{
MainContainer: {
justifyContent: ‘center’,
flex: 1,
backgroundColor: ‘#F5FCFF’,
margin: 10
}
});
|
Screenshot in Android device :
Screenshot in iOS Application :