-1

i use code same this best answer

Converting NSString to NSDate (and back again)

NSString *dateString = @"01-02-2010";
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
// this is imporant - we set our input date format to match our input string
// if format doesn't match you'll get nil from your string, so be careful
[dateFormatter setDateFormat:@"dd-MM-yyyy"];
NSDate *dateFromString = [[NSDate alloc] init];
// voila!
dateFromString = [dateFormatter dateFromString:dateString];

but dateFromString result is 2010-01-31 17:00:00 +0000 why it not same day.
i cannot compare date.

Community
  • 1
  • 1

3 Answers3

0

Its because of your current time zone, add this then it will give u correct date

[dateFormatter setTimeZone:[NSTimeZone timeZoneWithName:@"GMT"]];
Tj3n
  • 9,837
  • 2
  • 24
  • 35
0

Add the following line right after where you have set the date format. It because it will convert by default with local timezone of the device. It works for me!

[dateFormatter setTimeZone:[NSTimeZone timeZoneWithName:@"UTC"]];
Jaimish
  • 629
  • 5
  • 15
0

It is actually the same date. But the date formatter, by default, parses the date string in the local timezone of the device if a timezone is not passed in. In your case, your date was intepreted as Midnight February 2nd 2010 UTC+7 which is January 31st 2010 17:00 UTC.

If the date string is always in UTC, pass in the UTC timezone into the date formatter like this:

NSString *dateString = @"01-02-2010";
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"UTC"]];
// this is imporant - we set our input date format to match our input string
// if format doesn't match you'll get nil from your string, so be careful
[dateFormatter setDateFormat:@"dd-MM-yyyy"];
NSDate *dateFromString = [[NSDate alloc] init];
// voila!
dateFromString = [dateFormatter dateFromString:dateString];
Jose
  • 106
  • 4