[英]How to store start and end time and track them as history in React Native
每當我按下按鈕時,它都會顯示當前日期和時間。 我想要的是存儲這個日期和時間並擁有它的歷史。 就像在歷史中一樣,它將顯示正在存儲的日期和時間。 我有一個問題,不知道如何解決。 請指導我。 有什么鈎子嗎? 喜歡存儲歷史? 還是有其他好的方法? 請幫助我。 謝謝:)
import { useState } from "react";
import { View, Text, Button, StyleSheet} from "react-native";
export default function App() {
// Function for start time
const [starttime, setStarttime] = useState(false)
function getStartTimeString() {
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
}
// Function for end time
const [endTime, setEndtime] = useState(false)
function getEndTimeString() {
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
}
return (
<View style={styles.container}>
{
starttime &&
<>
<Text style={styles.text}>Start time</Text>
<Text style={styles.time}>{starttime}</Text>
</>
}
<Button
style={styles.button}
title='Start time'
onPress={() => setStarttime(getStartTimeString())
}
/>
{
endTime &&
<>
<Text style={styles.text}>End time</Text>
<Text style={styles.time}>{endTime}</Text>
</>
}
<Button
style={styles.button}
title='End time'
onPress={() => setEndtime(getEndTimeString())
}
/>
</View>
); }
const styles = StyleSheet.create({
container: {
marginTop: 90
},
text: {
backgroundColor: 'pink',
textAlign: 'center',
fontSize: 30,
padding: 20,
},
time: {
marginTop: 40,
padding: 20,
textAlign: 'center',
backgroundColor: 'blue',
color: 'white',
fontSize: 30
}
})
將您的時間存儲到一個數組中:
const [arrayStartTime, setArrayStartTime] = useState([])
function addNewStartTime(){
const tempArrayStartTime = [...arrayStartTime]
tempArrayStartTime.push(getStartTimeString())
setArrayStartTime([...tempArrayStartTime])
}
return(
//Rest fo your code
<Button
style={styles.button}
title='Start time'
onPress={() => addNewStartTime()}
/>
//Rest fo your code
)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.