netshark1000
netshark1000

Reputation: 7403

iOS Dateformatter Timezone

Im trying to convert a String without timezone value like "31.05.2015" to NSDate.

Whats wrong with my DateFormatter? It returns the date 2015-05-31 22:00:00 +0000 and when I try to print it with the same formatter it prints: 01.06.2015

-(NSDateFormatter*) dateFormatter{
    if(!_dateFormatter){
        _dateFormatter = [[NSDateFormatter alloc]init];
        [_dateAndTimeFormatter setDateFormat:@"dd.MM.yyyy"];
        [_dateAndTimeFormatter setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"CEST"]];
        _dateFormatter.dateStyle = NSDateFormatterShortStyle;
        _dateFormatter.timeStyle = NSDateFormatterNoStyle;
    }
    return _dateFormatter;
}

EDIT

I updated it to

-(NSDateFormatter*) dateAndTimeFormatter{
    if(!_dateAndTimeFormatter){
        _dateAndTimeFormatter = [[NSDateFormatter alloc]init];
        [_dateAndTimeFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss.SSS Z"];
        _dateAndTimeFormatter.dateStyle = NSDateFormatterShortStyle;
        _dateAndTimeFormatter.timeStyle = NSDateFormatterShortStyle;
    }
    return _dateAndTimeFormatter;
}

and call it with

NSDate *startDate = [self.dateFormatter dateFromString:@"31.05.2015"];
self.beginningValueLabel.text = [self.dateFormatter stringFromDate:startDate];

The result still is 01.06.2015.

startDate is 2015-05-31 22:00:00 +0000

Upvotes: 2

Views: 1805

Answers (1)

Kekoa
Kekoa

Reputation: 28240

When you use [NSDateFormatter setTimeZone:] the formatter will adjust the date for display based on that new timezone, so it's adding the timezone offset to the date before formatting it for display.

The NSDateFormatter defaults to the timezone of the device, so it would have had the same effect as setting the timezone manually. Tell the DateFormatter to use the same timezone as the date (+0000).

dateFormatter.timeZone = [NSTimeZone timeZoneForSecondsFromGMT:0]

Upvotes: 1

Related Questions