Objective-C setting NSDate to current UTC

IphoneObjective CIosNsdateUtc

Iphone Problem Overview


Is there an easy way to init an NSDate with the current UTC date/time?

Iphone Solutions


Solution 1 - Iphone

[NSDate date];

You may want to create a category that does something like this:

-(NSString *)getUTCFormateDate:(NSDate *)localDate
{
	NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
	NSTimeZone *timeZone = [NSTimeZone timeZoneWithName:@"UTC"];
	[dateFormatter setTimeZone:timeZone];
	[dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
	NSString *dateString = [dateFormatter stringFromDate:localDate];
    [dateFormatter release];
	return dateString;
}

Solution 2 - Iphone

NSDate is a reference to an interval from an absolute reference date, January 1, 2001 00:00 GMT. So the class method [NSDate date] will return a representation of that interval. To present that data in a textual format in UTC, just use the NSDateFormatter with the appropriate NSTimeZone (UTC) to render as needed.

Solution 3 - Iphone

NSDate objects encapsulate a single point in time, independent of any particular calendrical system or time zone. Date objects are immutable, representing an invariant time interval relative to an absolute reference date (00:00:00 UTC on 1 January 2001).

Swift version:

extension NSDate {
    func getUTCFormateDate() -> String {
        let dateFormatter = NSDateFormatter()
        let timeZone = NSTimeZone(name: "UTC")
        dateFormatter.timeZone = timeZone
        dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
        return dateFormatter.stringFromDate(self)
    }
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionBrodieView Question on Stackoverflow
Solution 1 - IphonejessecurryView Answer on Stackoverflow
Solution 2 - Iphonercw3View Answer on Stackoverflow
Solution 3 - IphoneTikhonov AleksandrView Answer on Stackoverflow