我正在创建一个应用,其中用户点击红色按钮,将时间戳更新为当前时间 - >按钮变为绿色 - >在时间戳后12小时,该按钮再次变为红色 - >并且循环继续。这是我的代码:
var timestampHour = 8
var timestampDay = 30
func getCurrentTime() {
let user = FIRAuth.auth()?.currentUser?.uid
var timeToFirebase = 0
var timeToDayEnd = 0
let currentHour = Calendar.current.component(.hour, from: Date())
let currentDay = Calendar.current.component(.day, from: Date())
//self.nameLabel.text = String(currentHour) + " " + String(currentHour)
if (currentDay - timestampDay >= 2) {
self.ref?.child("users").child(user!).child("timeToWatch").setValue(0)
self.ref?.child("users").child(user!).child("streakStatus").setValue("n")
}
else if (abs(currentDay - timestampDay) == 1) {
timeToDayEnd = 24 - timestampHour
timeToFirebase = timeToDayEnd + currentHour
if (timeToFirebase >= 12) {
self.ref?.child("users").child(user!).child("timeToWatch").setValue(0)
self.ref?.child("users").child(user!).child("streakStatus").setValue("n")
}
else {
self.ref?.child("users").child(user!).child("timeToWatch").setValue(timeToFirebase)
}
}
else {
timeToFirebase = currentHour - timestampHour
if (timeToFirebase >= 12) {
self.ref?.child("users").child(user!).child("timeToWatch").setValue(0)
self.ref?.child("users").child(user!).child("streakStatus").setValue("n")
}
else {
self.ref?.child("users").child(user!).child("timeToWatch").setValue(timeToFirebase)
}
}
}
我已经能够弄清楚如何找到一次与另一次之间的时差并采取相应的行动。但是,如何在用户第一次打开应用程序时创建时间戳,然后在用户在时间戳到当前时间戳后12小时打开应用程序时更新时间戳?我对如何制作时间戳感到困惑。
答案 0 :(得分:0)
如果您需要unix时间格式的时间戳,可以使用以下代码:
let currentDate = Date()
let timeStamp = currentDate.timeIntervalSince1970 //returns something like 1509411424.038336
如果您需要一些存储某些日期的逻辑,然后检查存储后是否过了12小时,您可以使用此代码:
func storeDate(_ date: Date) {
UserDefaults.standard.set(date.timeIntervalSince1970, forKey: "storedDate")
}
func getStoredDate() -> Date? {
if let timeStamp = UserDefaults.standard.value(forKey: "storedDate") as? Double {
return Date(timeIntervalSince1970: timeStamp)
}
return nil
}
func checkCurrentDate()-> Bool {
if let storedDate = getStoredDate() {
let nextDate = Date(timeInterval: 60 * 60 * 12, since: storedDate)
if nextDate < Date() {
return true
} else {
return false
}
} else {
storeDate(Date())
return true
}
}
如果您需要查找两个日期之间的小时差异,可以使用此代码:
let aDate = Date(timeIntervalSinceReferenceDate: 0)
let bDate = Date(timeIntervalSinceReferenceDate: 60 * 60 * 12)
let hoursDiff = Calendar.current.dateComponents([.hour], from: aDate, to: bDate).hour ?? 0