Skip to content

Instantly share code, notes, and snippets.

@jen2
Last active May 7, 2017 16:11
Show Gist options
  • Save jen2/a8a409d80a4e78af59e7f82eab1fa7ea to your computer and use it in GitHub Desktop.
Save jen2/a8a409d80a4e78af59e7f82eab1fa7ea to your computer and use it in GitHub Desktop.
Date and time formatting with the formatCurrentDateTimeForTimeZone method for "Build a World Clock in Objective-C."
-(NSArray *)formatCurrentDateTimeForTimeZone { //Gets current date each time it's fired.
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
NSDateFormatter *timeFormatter = [[NSDateFormatter alloc] init];
NSLocale *posix = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"];
NSTimeZone *localTimeZone = [NSTimeZone timeZoneWithAbbreviation:self.timeZone];
[dateFormatter setLocale:posix];
[dateFormatter setDateFormat:@"EEEE MMMM dd y"];
[dateFormatter setTimeZone:localTimeZone];
[timeFormatter setLocale:posix];
[timeFormatter setDateFormat:@"h:mm:ss a"];
[timeFormatter setTimeZone:localTimeZone];
NSDate *now = [NSDate date];
NSString *date = [dateFormatter stringFromDate:now];
NSString *time = [timeFormatter stringFromDate:now];
NSArray *formattedDateAndTime = @[date, time];
return formattedDateAndTime;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment