-1

I am making NSDate from this string but Every time I am getting Previous Month from Selected Month

I am not able to find the bug:

  NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];

  [dateFormatter setTimeZone:[NSTimeZone defaultTimeZone]];

  [dateFormatter setDateFormat:@"dd/MMM/yyyy"];

  NSDate *date = [dateFormatter dateFromString:strDate];

  NSLog(@"------Date----%@",date);

I have tried with many Datestrings some are with Logs are:

  strDate =---- 01/Jan/2016
  ------Date----2015-12-31 18:30:00 +0000

  strDate =----01/Dec/2015
  ------Date----2015-11-30 18:30:00 +0000
Rahul
  • 5,594
  • 7
  • 38
  • 92

1 Answers1

1

As viking says, what you are seeing is an artifact of the way you are displaying your resulting date. When you log an NSDate object in NSLog, it is always displayed in UTC. If your date does not have a time component, midnight is assumed. If your time zone is AFTER UTC, midnight in your time zone will be displayed as the previous day.

I suggest you create a display date formatter to display your resulting dates, and use that:

- (NSString *) displayStringForDate: (NSDate *) date
{
   static NSDateFormatter *dateFormatter;
   if (dateFormatter == nil)
   {
     //This date formatter will default to the current time zone, like you want.
     dateFormatter = [[NSDateFormatter alloc]init];
     //Adjust the date format as desired
   {
   return [dateFormatter stringFromDate: date];
}

Then use that method in your test code:

NSLog(@"------Date----%@", [self displayStringForDate: date]);
Duncan C
  • 128,072
  • 22
  • 173
  • 272