首页 > 解决方案 > 日期未获取手机 Swift 4 的当前时间

问题描述

我有这个函数可以计算电话当前分钟的时间量。我正试图在这段特定的时间后让计时器响起。调用此函数的方式是通过用户在应用程序中翻转的开关,时间应自行重置。好吧,当之前翻转开关时,我的 NSDate 对象获取旧值时遇到问题。有没有办法将 NSDate 对象重置为零?

这是我计算手机当前时间的代码。

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 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]()

标签: swiftnsdate

解决方案


您的代码使用的date是一个 let 常量的实例变量。您没有显示设置它的上下文,但我假设它是您的类的实例变量。它是一个 let 常量这一事实意味着它在声明它的范围内永远不会改变。这几乎肯定是你的问题。


推荐阅读