skip to Main Content
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'
        
    }

});

3

Answers


  1. Remove the useEffect and handle the state change in the onPress function of the Button. The state change will trigger a rerender of the whole component and the new date will be visible.

    function getCurrentDateString() {
        const date = new Date().getDate() //current date
        const month = new Date().getMonth() + 1 //current month
        const year = new Date().getFullYear() //current year
        const hours = new Date().getHours() //current hours
        const min = new Date().getMinutes() //current minutes
        const sec = new Date().getSeconds() //current seconds
    
        return date + '/' + month + '/' + year + '    ' +  hours + ':' + min + ':' + sec
    }
    
    export default function App() {
       // set the date initially on mount
       const [currentdate, setCurrentdate] = useState(getCurrentDateString())
    
      return (
        <View style={styles.container}>
            <Text>Showing current date and time</Text>
            <Text style={styles.date}>{currentdate}</Text>
            <Button 
              title='hit me' 
              onPress={() => setCurrentdate(getCurrentDateString()}
              }/>
    
        </View>
    
      );
    
    Login or Signup to reply.
  2. Install momentjs

    npm install --save moment
    

    Import momentjs

    import moment from "moment";
    

    Button

    <Button 
      title='hit me' 
      onPress={() => setCurrentDate(new Date())} 
    />
    

    Text

    <Text style={styles.date}>{currentDate ? moment(currentDate).format("YYYY-MM-DD HH:mm:ss") : ''}</Text>
    

    NOTE: Remove also useEffect please

    Further reading

    momentjs

    Login or Signup to reply.
  3. Here you a solution with Intl

    import { useCallback, useState } from 'react';
    import { StyleSheet, Text, View, Button } from 'react-native';
    export default function App() {
    
        const [currentdate, setCurrentdate] = useState(null)
    
      const handleGenerateDateTime = useCallback(() => {
        setCurrentdate(new Intl.DateTimeFormat('en-GB', {day: "numeric", month:"numeric", year:"numeric",hour: "numeric", minute:"numeric", second:"numeric"}).format());
      }, [])
    
      return (
    
        <View style={styles.container}>
            {currentdate &&
              <>
                <Text>Showing current date and time</Text>
                <Text style={styles.date}>{currentdate}</Text>
              </>
            }
    
            <Button 
              title='hit me' 
              onClick={handleGenerateDateTime}
            />
    
        </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'
            
        }
    
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

    Documentation: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/DateTimeFormat

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search