I want to show the current time(MM/DD/YY hh:mm:ss) in react native app like a clock, and get update every seconds, I tried using new Date() and set it in state, but the time don't update unless I refresh the page. I also tried using setInterval function in render(), it do got update but it's expensive for CPU. is there a good method to realise the function?
state = { curTime: null, } render(){ setInterval(function(){this.setState({curTime: new Date().toLocaleString()});}.bind(this), 1000); return ( <View> <Text style={headerStyle.marginBottom15}>Date: {this.state.curTime}</Text> </View> ); }
To get the current datetime in react native has the Date() object it will return every time the current date and time when we use it. we have to just write new Date() and it returns the date object where we get a year, month, date, hours, minutes, and seconds.
To show current time and update the seconds in real time with React Native, we can use the setInterval function to update the time every second. to call setInterval with a callback that calls setTime with new Date(). toLocaleString() to set time to the current date time string.
To update React component every second with JavaScript, we can use the setInterval function to update a state in the useEffect hook. const [time, setTime] = useState(Date. now()); useEffect(() => { const interval = setInterval(() => setTime(Date.
setInterval(() => { window. location. reload(); }, 5000);
Just move setInterval
into componentDidMount function.
Like this :
componentDidMount() { setInterval(() => { this.setState({ curTime : new Date().toLocaleString() }) }, 1000) }
This will change state and update every 1s.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With