Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

431
Visualizações
How to show date and time when I press the button? (onPress)
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'
        
    }

});
about 4 years ago · Santiago Trujillo
3 Respostas
Responde à pergunta

0

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>

  );
about 4 years ago · Santiago Trujillo Relatório

0

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

about 4 years ago · Santiago Trujillo Relatório

0

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

about 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda