The best way to manage dates, times, and time zones is to store everything in the database as Coordinated Universal Time (UTC) then present it back to the user in a local format. The clear benefit is that it reduces any mistakes when working through "daylight savings time."
Swift works well with Apple's NSCalendar
, and here's how to capture the current time in UTC format.
import Foundation
let date = NSDate()
if let utcCalendar = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian) {
if let utcTimeZone = NSTimeZone(abbreviation: "UTC") {
utcCalendar.timeZone = utcTimeZone
let ymdhmsUnitFlags: NSCalendarUnit = .YearCalendarUnit | .MonthCalendarUnit | .DayCalendarUnit | .HourCalendarUnit | .MinuteCalendarUnit | .SecondCalendarUnit
let utcDateComponents = utcCalendar.components(ymdhmsUnitFlags, fromDate: date)
// Create string of form "yyyy-mm-dd hh:mm:ss"
let utcDateTimeString = NSString(format: "%04u-%02u-%02u %02u:%02u:%02u",
UInt(utcDateComponents.year),
UInt(utcDateComponents.month),
UInt(utcDateComponents.day),
UInt(utcDateComponents.hour),
UInt(utcDateComponents.minute),
UInt(utcDateComponents.second))
}
}
Swift: Do Try Catch
I've discovered that there are really two ways to accomplish a Try/Catch strategy in Swift. The first example is technically correct but the "shorthand&...
Subscribe to new posts
Processing your application
Please check your inbox and click the link to confirm your subscription
There was an error sending the email