Reputation: 111
I am taking an NSDate, and pulling just a 2-digit number, representing the day of the month into an NSString. One of the dates in question is:
2013-11-30 00:00:00 +0000
I use:
NSDateFormatter *formatter2 = [[NSDateFormatter alloc] init];
[formatter2 setDateFormat:@"dd"];
NSString *datefromdate = [formatter2 stringFromDate:articleDate];
NSLog(@"Date%@", datefromdate);
[formatter2 release];
but the log comes back
29
Upvotes: 1
Views: 516
Reputation: 112873
Set the timezone you want the time date formatter to use. NSDate is the first instant of 1 January 2001, GMT and thus has no timezone information in it.
So, this, according to Apple, is going to get complicated needing up to five classes: NSDateFormatter
, NSDate
, NSCalendar
, NSTimeZone
and finally NSDateComponents
.
If all you want is the day you can use NSDateComponents
.
Example:
NSString *dateString = @"2013-11-30 00:00:00 +0000";
NSDateFormatter *inDateFormatter = [[NSDateFormatter alloc] init];
[inDateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss Z"];
NSDate *date = [inDateFormatter dateFromString:dateString];
NSLog(@"dateFromString: %@", date);
NSTimeZone *timezone = [NSTimeZone timeZoneForSecondsFromGMT:0];
// Using date formatter, result is a string
NSDateFormatter *outDateFormatter = [NSDateFormatter new];
[outDateFormatter setTimeZone:timezone];
[outDateFormatter setDateFormat:@"dd"];
NSString *dayString = [outDateFormatter stringFromDate:date];
NSLog(@"date formatter day: %@", dayString);
// Using date components, result is an integer
NSCalendar *calendar = [NSCalendar currentCalendar];
[calendar setTimeZone: timezone];
NSDateComponents *dateComponents = [calendar components:NSDayCalendarUnit fromDate:date];
NSInteger day = [dateComponents day];
NSLog(@"date components day: %i", day);
NSLog output:
dateFromString: 2013-11-30 00:00:00 +0000
date formatter day: 30
date components day: 30
Upvotes: 2
Reputation: 42614
You are probably in a negative time zone i.e. GMT minus something. This is why 2013-11-30 00:00:00 +0000 GMT
is on the 29th day when you log it. Set the formatter to GMT and you will be fine.
Upvotes: 8