Last active
December 8, 2017 12:31
-
-
Save kristopherjohnson/dc088c022f11da3fbc54 to your computer and use it in GitHub Desktop.
Get UTC date/time string for current time using NSCalendar
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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]]; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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)) | |
} | |
} |
No '|' candidates produce the expected contextual result type 'NSCalendarUnit' in swift 2.1
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
Thank you for this time saver!