0

Team,

When converting NSString to NSDate it give me wrong result.

NSDateFormatter * formatter = [NSDateFormatter new];
[formatter setDateFormat:@"yyyy-MM-dd"];
NSString * currentDateString = [formatter stringFromDate:[NSDate date]];
NSDate *currentDate = [formatter dateFromString:currentDateString];

currentDateString value is "2017-01-01" currentDate value is getting 2016-12-31 18:30:00 +0000

It was surprise for me is any thing wrong with in converstion?

kiran
  • 4,285
  • 7
  • 53
  • 98

2 Answers2

1

Problem is that you haven't added timezone for date formatter. Update your code with following one:

NSDateFormatter * formatter = [NSDateFormatter new];
[formatter setDateFormat:@"yyyy-MM-dd"];
[formatter setTimeZone:[NSTimeZone timeZoneWithName:@"UTC"]];
NSString * currentDateString = [formatter stringFromDate:[NSDate date]];
NSDate *currentDate = [formatter dateFromString:currentDateString];

Now values will be

currentDateString = "2016-12-30"

currentDate = 2016-12-30 00:00:00 +0000

Pushkraj Lanjekar
  • 2,254
  • 1
  • 21
  • 34
  • Only do this if you want the date string to be interpreted as UTC time instead of local time. – rmaddy Dec 30 '16 at 14:31
1

Call below method with the Timezone string in which you want the date & this method will return you date of that particular timezone.

-(NSString *)getCurrentDateForTimeZone:(NSString *)timeZone{
    NSDate *currentDate = [[NSDate alloc] init];
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd"];
    [dateFormatter setTimeZone:[NSTimeZone timeZoneWithName:timeZone]];// Your timezone
    NSString *localDateString = [dateFormatter stringFromDate:currentDate];
    return localDateString;
}

This method will return you current date of the timezone which you have passed.

EDIT: If you need time along with date then modify the dateFormatter to

[dateFormatter setDateFormat = @"yyyy-MM-dd hh:mm:ss a"]; // you can modify the format with the way you want
iYoung
  • 3,596
  • 3
  • 32
  • 59