How to make a countdown to date Swift

前端 未结 4 492
青春惊慌失措
青春惊慌失措 2021-02-03 16:03

I was facing the struggle of making a timer app, so I thought that now that I solved it I could help others who face the problem. So basically this app counts down to a specific

4条回答
  •  暖寄归人
    2021-02-03 16:40

    This worked for me. The only thing that troubles me is that it doesn't really countdown as the user has to refresh the page for it to recount. You can see it "counting" when the user is scrolling up and down cells on a UITableView as the cells do refresh the view. Another thing is that I have on NSTimeZone of the currentDate "GMT+2:00" as it works for my time but only because I haven't figured out how to use the device NSTimeZone yet.

        let releaseDate = "2015-05-02'T'22:00:00:000Z"
        let futureDateFormatter = NSDateFormatter()
        futureDateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"
        let date: NSDate = futureDateFormatter.dateFromString(releaseDate!)!
    
        let currentDate = NSDate();
        let currentFormatter = NSDateFormatter();
        currentFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"
        currentFormatter.timeZone = NSTimeZone(abbreviation: "GMT+2:00")
    
        let diffDateComponents = NSCalendar.currentCalendar().components([NSCalendarUnit.Month, NSCalendarUnit.Day, NSCalendarUnit.Hour, NSCalendarUnit.Minute], fromDate: currentDate, toDate: date, options: NSCalendarOptions.init(rawValue: 0))
    
        let countdown = "\(diffDateComponents.month) m: \(diffDateComponents.day) d: \(diffDateComponents.hour) h: \(diffDateComponents.minute) min"
    

提交回复
热议问题