Firemarble Firemarble - 9 months ago 38
iOS Question

How to remove the timezone offset from an NSDate

I am trying to get just

yyyy-MM-dd HH:mm
from an NSDateFormatter.

But the string spits out
Historical Date: 2016-08-23 14:03:00 +0000

I do not want the seconds or the +0000.

What am I doing wrong?

int seconds = -( days * (24 * 60 * 60)); //24 hours, times 60 minutes, times 60 seconds
NSDateFormatter *format = [[NSDateFormatter alloc] init];
[format setDateFormat:@"yyyy-MM-dd HH:mm"];

NSString* stringFromDate = [format stringFromDate:[NSDate date]];
NSDate * pastDate = [[format dateFromString:stringFromDate] dateByAddingTimeInterval:seconds];

NSLog(@"Date: %@", pastDate);


It happens because you printing NSDate object. NSDate object encapsulates a single point in time, it is not responsible for it's string representation. What you really need to do, is to calculate exact date you need, and then format it into NSString.

Something like that:

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm"];
NSDate *pastDate = [[NSDate date] dateByAddingTimeInterval:seconds];

NSString *yourDateInString = [dateFormatter stringFromDate:pastDate];
NSLog(@"%@", yourDateInString);

Also, it is good practice to use NSCalendar and NSCalendarComponents to manipulate with dates and calculate new dates instead of just adding time interval.