Search code examples
nsdatensdateformatternstimeinterval

NSTimeInterval since1970 to NSDate


I have the following code:

-(void)setDate:(double)dateInterval {
    NSDate *date = [NSDate dateWithTimeIntervalSince1970:(NSTimeInterval)dateInterval];
    NSLog(@"NSDate-Result: %@", [date description]);

    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateStyle:NSDateFormatterMediumStyle];
    [formatter setTimeStyle:NSDateFormatterMediumStyle];

    [formatter setFormatterBehavior:NSDateFormatterBehavior10_4];
    [formatter setDateFormat:@"YYYY-MM-DD HH:mm:SS"];

    NSString *dateString = [formatter stringFromDate:date];
    NSLog(@"String-Result: %@", dateString);

    date_label.text = dateString;
}

in NSDate the Date is correct, but the converted string isn't correct anymore.

Results:

2012-08-03 10:58:40.469 iSkizzenaufmass[4148:c07] NSDate-Result: 2012-08-03 08:08:35 +0000 2012-08-03 10:58:40.471 iSkizzenaufmass[4148:c07] String-Result: 2012-08-216 10:08:48


Solution

  • You have to use yyyy-MM-dd HH:mm:SS instead of -DD (DD is day of the year)

    EDIT: changed YYYY to yyyy as YYYY is week based year and could differ from current year (see link below for all opts)