import { useEffect, useState } from 'react';
import { StyleSheet, Text, View, Button } from 'react-native';
export default function App() {
const [currentdate, setCurrentdate] = useState('')
useEffect(() => {
var date = new Date().getDate() //current date
var month = new Date().getMonth() + 1 //current month
var year = new Date().getFullYear() //current year
var hours = new Date().getHours() //current hours
var min = new Date().getMinutes() //current minutes
var sec = new Date().getSeconds() //current seconds
setCurrentdate(
date + '/' + month + '/' + year + ' ' + hours + ':' + min + ':' + sec
)
}, )
return (
<View style={styles.container}>
<Text>Showing current date and time</Text>
{/* <Text style={styles.date}>{currentdate}</Text> */}
<Button
title='hit me'
onPress={() => {<Text style={styles.date}>{currentdate}</Text>}
}/>
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#fff',
alignItems: 'center',
justifyContent: 'center',
},
date: {
fontSize: 35,
marginTop: 30,
paddingHorizontal: 30,
borderWidth: 2,
borderColor: 'black',
color: 'blue'
}
});
Question posted in React native
The official React Native documentation can be found here.
The official React Native documentation can be found here.
3
Answers
Remove the
useEffect
and handle the state change in theonPress
function of theButton
. The state change will trigger a rerender of the whole component and the new date will be visible.Install momentjs
Import momentjs
Button
Text
NOTE: Remove also useEffect please
Further reading
momentjs
Here you a solution with Intl
Documentation: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/DateTimeFormat