Skip to content

Instantly share code, notes, and snippets.

@cieslak
Last active December 10, 2015 13:09
  • Star 3 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save cieslak/4439267 to your computer and use it in GitHub Desktop.
Date Formatting String Example
#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;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment