public
Last active

Date Formatting String Example

  • Download Gist
main.m
Objective-C
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
#import <Foundation/Foundation.h>
 
int main(int argc, const char * argv[])
{
 
@autoreleasepool {
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateFormatter *df = [[NSDateFormatter alloc] init];
// Note the uppercase Y's in this date formatter string
[df setDateFormat:@"YYYY-MM-dd HH:mm:ss"];
// Date components for New Year's Eve, 2012
NSDateComponents *components = [[NSDateComponents alloc] init];
[components setYear:2012];
[components setMonth:12];
[components setDay:31];
NSDate *nye = [gregorian dateFromComponents:components];
// Logged to console as NSDate
NSLog(@"NYE as NSDate: %@", nye);
// Now as a formatted string. If you run this before 2013/1/7, it will return 2013 in the year field.
NSString *dateStr = [df stringFromDate:nye];
NSLog(@"NYE as formatted string: %@", dateStr);
// Here's the issue. Turn the string back into an NSDate, but using lowercase y's in the string.
[df setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
NSDate *reconstitutedDate = [df dateFromString:dateStr];
NSLog(@"NYE as new NSDate from string: %@", reconstitutedDate);
}
return 0;
}

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.