Skip to content

Instantly share code, notes, and snippets.

@kristopherjohnson
Last active December 8, 2017 12:31
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kristopherjohnson/dc088c022f11da3fbc54 to your computer and use it in GitHub Desktop.
Save kristopherjohnson/dc088c022f11da3fbc54 to your computer and use it in GitHub Desktop.
Get UTC date/time string for current time using NSCalendar
NSDate *date = [NSDate date];
NSCalendar *utcCalendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
utcCalendar.timeZone = [NSTimeZone timeZoneWithAbbreviation:@"UTC"];
unsigned ymdhmsUnitFlags = NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay| NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond;
NSDateComponents *utcDateComponents = [utcCalendar components:ymdhmsUnitFlags fromDate:date];
// Create string of form "yyyy-mm-dd hh:mm:ss"
NSString *utcDateTime = [NSString stringWithFormat:@"%04lu-%02lu-%02lu %02lu:%02lu:%02lu",
(unsigned long)[utcDateComponents year],
(unsigned long)[utcDateComponents month],
(unsigned long)[utcDateComponents day],
(unsigned long)[utcDateComponents hour],
(unsigned long)[utcDateComponents minute],
(unsigned long)[utcDateComponents second]];
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))
}
}
@chrisjmendez
Copy link

Thank you for this time saver!

@shejis
Copy link

shejis commented May 5, 2016

No '|' candidates produce the expected contextual result type 'NSCalendarUnit' in swift 2.1

@karmaios
Copy link

karmaios commented Jun 2, 2016

let ymdhmsUnitFlags: NSCalendarUnit = [NSCalendarUnit.Year , .Month ,.Day,.Hour , .Minute , .Second]

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment