Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

iOS

how to set to a certain time zone on swift

the below code works fine and it is a timer function which counts down to midnight. how can i go about locking this to a time zone. where it will still count down to the same time even if the time zone on the phone changes

  func updateTimeGMT(){

    let now = NSDate()
    let timezoneLK = NSTimeZone(forSecondsFromGMT: 19800)


    let calendar = NSCalendar.autoupdatingCurrentCalendar()
    //let calendar = NSCalendar()
    calendar.componentsInTimeZone(timezoneLK, fromDate: now)

    var startOfDay = NSDate?()
    var lengthOfDaySeconds : NSTimeInterval = 0

    if (calendar.rangeOfUnit(NSCalendarUnit.CalendarUnitDay, startDate:&startOfDay, interval:&lengthOfDaySeconds, forDate: now)) {
            let endOfDay = startOfDay?.dateByAddingTimeInterval(lengthOfDaySeconds)

            println("\(now) : \(endOfDay!)")

            if let secondsUntilEndOfDay = endOfDay?.timeIntervalSinceDate(now) {
                var timeLeft = secondsUntilEndOfDay
                let hours = floor(timeLeft / 3600.0)
                timeLeft -= (hours * 3600.0)
                let minutes = floor(timeLeft / 60.0)
                timeLeft -= (minutes * 60.0)
                let seconds = floor(timeLeft)
                timeLeft -= seconds
                let fraction = floor(timeLeft * 100)

                let strHours = String(format: "%02d", UInt(hours))
                let strMinutes = String(format: "%02d", UInt(minutes))
                let strSeconds = String(format: "%02d", UInt(seconds))
                let strFraction = String(format: "%02d", UInt(fraction))

                countingLabel.text = "\(strHours) : \(strMinutes) : \(strSeconds) : \(strFraction)"
            }
        }
    }

1 Answer

Mugunthan,

Your going to want to use NSTimeZone

Check out This link