日期未获取手机的当前时间Swift 4
我有这个功能,可以计算手机当前分钟的时间。我试图让计时器在这段特定的时间后熄灭。调用此函数的方式是通过用户在应用程序中翻转的开关,时间应自行重置。当开关之前被翻转时,我的NSDate对象无法获得旧值。有没有办法将NSDate对象重置为零 这是我计算手机当前时间的代码日期未获取手机的当前时间Swift 4,swift,nsdate,Swift,Nsdate,我有这个功能,可以计算手机当前分钟的时间。我试图让计时器在这段特定的时间后熄灭。调用此函数的方式是通过用户在应用程序中翻转的开关,时间应自行重置。当开关之前被翻转时,我的NSDate对象无法获得旧值。有没有办法将NSDate对象重置为零 这是我计算手机当前时间的代码 func GetInitialTime(){ finalTime = 0 firstTimeCounter = 0 timeInSeconds = 0 let calendar = NSCalenda
func GetInitialTime(){
finalTime = 0
firstTimeCounter = 0
timeInSeconds = 0
let calendar = NSCalendar.current
var minutes = calendar.component(.minute, from: date)
var timeDifference = Int()
if(minutes == 00 || minutes == 30) {
print("The minute hand is at zero or thirty.")
}
else {
print("The minute hand is NOT ar zero or thirty")
print("The minute hand ia at:")
if minutes < 30 {
while (!(minutes == 30)) {
minutes += 1
timeDifference += 1
}
print("Therefore we make the minute hand at zero or thiry: ", minutes)
print("The time difference we add to the minute is: ", timeDifference)
}
else {
var i = minutes
while i < 60 {
i += 1
minutes += 1
timeDifference += 1
}
print("Therefore we make the minute hand at zero or thirty: ", minutes)
print("The Time difference we add to the minute is: ", timeDifference)
}
}
finalTime = Double(timeDifference * 60)
print("The time difference in seconds is:", finalTime)
}
您的代码正在使用一个实例变量
date
,它是一个let常量。您没有显示设置它的上下文,但我假设它是类的实例变量。事实上,它是一个let常量,这意味着它在声明的范围内永远不会改变。这几乎肯定是你的问题 你能告诉我你在哪里申报日期吗?使用Date()可以立即给出时间。这是一种快捷方式,请使用Calendar
,而不是NSCalendar
。不要使用NSDate
,使用Date
。哎呀,我是说Date。我用的是DateYes,就是这样。我在GetInititalTime()函数中声明了它,并将其更改为var,现在它可以完美地工作了!谢谢欢迎来到SO。如果你问了一个问题,有人给出了解决问题的答案,你应该接受这个答案。这是一个强大的大会在这个网站上。(如果有多个正确答案,您应该接受第一个正确答案,或者如果后面的答案明显优于第一个正确答案,您应该接受最佳答案。)
let center = UNUserNotificationCenter.current()
let button = UIButton(type: UIButtonType.custom)
let date = Date()
var timeInSeconds = Int()
var finalTime = Double()
var halfHour = Double(1800)
var firstTimeCounter = Int()
var firstTimer = Timer()
var repeatingTimer = Timer()
var backgroundTask = BackgroundTask()
let dispatchGroup = DispatchGroup()
var urlWeb = "http://morrowrenewablesflowdata.com/iOSConnections/Notifications.php"
var downtimes = [String]()
var flows = [String]()