Skip to content

@cieslak /main.m
Last active

Embed URL

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
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
Something went wrong with that request. Please try again.