drbj drbj - 1 month ago 7
iOS Question

NSDateFormatter adds excess time

I am trying to get the current day in MMMM dd, EEEE format. And here's what I've done

NSDate *utc = [[NSDate alloc] init];
NSDateFormatter *fmt = [[NSDateFormatter alloc] init];
NSTimeInterval timeZoneSeconds = [[NSTimeZone localTimeZone] secondsFromGMT];
NSDate *DateInLocalTimezone = [utc dateByAddingTimeInterval:timeZoneSeconds];
fmt.dateFormat = @"MMMM dd, EEEE";
NSString *currentDate = [fmt stringFromDate:DateInLocalTimezone];


Given,


  • utc = 2016-10-07 08:55:55 +0000

  • Timezone = gmt+8

  • DateInLocalTimezone = 2016-10-07 16:55:55 +0000

  • currentDate = October 08, Saturday



currentDate must be October 07, Friday. Why does it add another day when I format my date?

Answer

Try this:

NSDate *now = NSDate.date;
NSDateFormatter *fmt = NSDateFormatter.new;

fmt.dateFormat = @"MMMM dd, EEEE";

NSString *currentDate = [fmt stringFromDate:now];