ChrisM
ChrisM

Reputation: 329

Converting string to date looses an hour

I am trying to convert a date in string format to a NSDate, however the result seems to deduct an hour from the time passed in. Any ideas why?

-(NSDate *) convertStringToDate:(NSString *)theString {

    //init formatter
    NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init]; 

    //setup the formatter
    [dateFormat setDateFormat:@"dd-MM-yyyy HH:mm"];
    [dateFormat setTimeZone:[NSTimeZone localTimeZone]];  

    //cast the date from the string
    NSDate *date = [dateFormat dateFromString:theString];


    [dateFormat release];

    return date;    
}

this is the test call:

NSDate *testDate = [self convertStringToDate:@"28-03-2012 11:46"];    
NSLog(@"converted test date - %@", testDate);

i get the output (which is an hour before the time i specified as an argument):

converted test date - 2012-03-28 10:46:00 +0000

any help how i change the timezone would be appreciated.

Upvotes: 2

Views: 1305

Answers (2)

yuji
yuji

Reputation: 16725

When you NSLog an NSDate, it's not displayed in your local timezone. It's displayed in GMT. Your local timezone is currently 1 hour ahead of GMT (possibly because of daylight savings).

To convert the date to a string relative to your local timezone, you want to use a date formatter (the date formatter's timezone will be set to your local timezone by default):

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
dateFormatter.dateFormat = @"yyyy-MM-dd'T'HH:mm";
NSLog(@"converted test date - %@", [dateFormatter stringFromDate:testDate]);

Upvotes: 4

Antonio MG
Antonio MG

Reputation: 20410

You see one hour less because of your timezone, you need to change it when you get the date.

    DateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    dateFormatter.dateFormat = @"yyyy-MM-dd'T'HH:mm";

    NSTimeZone *gmt = [NSTimeZone timeZoneWithAbbreviation:@"GMT"];
    [dateFormatter setTimeZone:gmt];
    NSString *timeStamp = [dateFormatter stringFromDate:[NSDate date]];
    [dateFormatter release];

Upvotes: 1

Related Questions