Swift: UTC date/time string for current time

Coordinated universal time UTC in Swift.

Swift: UTC date/time string for current time

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",