1

I try to convert my NSString to NSDate object, but NSDateFormatter returns me a strange value.

Here is code:

NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:@"yyyy-MM-dd HH:mm"]; 
NSDate *date = [dateFormat dateFromString:@"2012-08-15 00:00"];
[dateFormat release];

date value is 2012-08-14 21:00 +0000. It is 3 hours difference between NSString value and NSDate value. I think I've missed something, but I don't know what.

Timur Mustafaev
  • 4,869
  • 9
  • 63
  • 109

4 Answers4

6

This is what i use:

NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:@"yyyy-MM-dd HH:mm:ss ZZZ"]; 

NSDate *date = [dateFormat dateFromString:@"2012-08-15 00:00:00 +0000"];
NSLog(@"\n\n  DATE: %@ \n\n\n", date);

The +0000 is timezone, so make sure you use your timezone, like +0400.

Edit: If you can't change the string, you can use this code to do it:

NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:@"yyyy-MM-dd HH:mm"]; 
[dateFormat setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];

NSDate *date = [dateFormat dateFromString:@"2012-08-15 00:00"];
Adam
  • 26,549
  • 8
  • 62
  • 79
0

As i knew NSDate holds Grinwich time, so if you are in Moscow time zone, everything is wright

mas'an
  • 170
  • 6
0

In objective c for NSDate if you did not set the setTimeZone, NSDate will take default timezone as localTimeZone. so if you need to get the exact date which you give as NSString string format, you need to setTimeZone as UTC. Follow the sample code, I guess it will be helpful for you.

NSDateFormatter *loacalformatter=[[NSDateFormatter alloc]init];
[loacalformatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
NSDate *localDate =[loacalformatter dateFromString:@"2012-08-15 00:00"];
NSLog(@"localDate :%@",localDate);


NSDateFormatter *UTCformatter=[[NSDateFormatter alloc]init];
[UTCformatter setTimeZone:[NSTimeZone timeZoneWithName:@"UTC"]];
[UTCformatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
NSDate *UTCDate =[UTCformatter dateFromString:@"2012-08-15 00:00"];
NSLog(@"UTCDate :%@",UTCDate);
UTCDate :2012-08-15 00:00 +0000 (GMT+00:00)
Prashanth Rajagopalan
  • 718
  • 1
  • 10
  • 27
-1

As suggested in the comments, if the date you receive is UTC then you need to convert it to your local timezone. Apple recommend you always use a properly configured NSDateFormatter when displaying dates, to handle localisation issues.

Here's some example code for turning an NSDate into an NSString:

NSDate *date = // initialised elsewhere

NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
dateFormat.locale = [NSLocale currentLocale];
dateFormat.timeZone = [NSTimeZone localTimeZone];
dateFormat.timeStyle = NSDateFormatterShortStyle;
dateFormat.dateStyle = NSDateFormatterShortStyle;    
dateFormat.locale = [NSLocale currentLocale];
NSString *dateAsString = [dateFormat stringFromDate:date];
ChrisH
  • 904
  • 6
  • 13