4

I have this piece of code:

NSDateFormatter* df = [[NSDateFormatter alloc] init];
df.locale = [NSLocale currentLocale];
df.timeZone = [NSTimeZone localTimeZone];
df.timeStyle = NSDateFormatterShortStyle;
df.dateStyle = NSDateFormatterShortStyle;
df.locale = [NSLocale currentLocale];
[df setDateFormat:@"dd/MM/yyyy"];
NSString *todaysDate = @"31/12/2013";
NSDate* today = [df dateFromString:todaysDate];

NSLog(@"comparing todaysDate: %@ with today: %@",todaysDate,today);

When I check my console I see that todaysDate is 31/12/2013 and today is 2013-12-30 21:00:00 +0000 I do not understand why it goes 1 day into the past... can anyone help me out here? I'm trying to basically filter out some items in a dictionary based on date. Filtering part not included here as it was determined that the dateFromString is not doing its job.

MikeS
  • 161
  • 1
  • 6
  • Check in your device that Settings->General->Date& time-> Time zone and device that Settings->General->International->Region formats – jailani Dec 31 '13 at 09:37
  • Yes, it is issue with your time settings. The code is perfect when checked in online Objective C compiler – TryinHard Dec 31 '13 at 09:41
  • "31/12/2013" in your time zone is the same as "2013-12-30 21:00:00 +0000" (which reports the time in UTC). - This is asked and answered frequently, see above "possible duplicate" or google for "NSDate wrong". – Martin R Dec 31 '13 at 09:41

3 Answers3

9

It's very probably because of your TimeZone. You seems to be GMT+3 or something like that. If you change your local Time Zone things should be ok.

You should use : df.timeZone = [NSTimeZone timeZoneForSecondsFromGMT:0]: instead of localTimeZoneto always have the same results even in different time zones.

Zaphod
  • 6,758
  • 3
  • 40
  • 60
2

Add the below to your NSDateFormatter.

[df setTimeZone:[NSTimeZone timeZoneWithName:@"GMT"]];
thatzprem
  • 4,697
  • 1
  • 33
  • 41
-4

When I program with dates I always use this code, I'm sorry but I can't help you with NSString to NSDate because I don't use that code myself

hire is solution to your problem:

#include <ctime>
#include <iostream>
using namespace std;

int main() {
time_t t = time(0);   // get time now
struct tm * now = localtime( & t );
cout << (now->tm_year + 1900) << '-' 
     << (now->tm_mon + 1) << '-'
     <<  now->tm_mday
     << endl;
}
user3137147
  • 243
  • 1
  • 4
  • 8
  • If you know exact answer or little bit relevant to answer. Then only post your answer here. It's totally irrelevant. Do you know xcode tool ? – Mani Dec 31 '13 at 09:42
  • This is not an answer. – san Dec 31 '13 at 09:50