Jeff W
Jeff W

Reputation: 568

Trouble converting NSString to a NSDate

I have looked at other examples and I am still not able to convert this string to a date. After i run this code I get the following output from the NSLogs:

Prediction Conversion: 2012-07-01 00:00:00 +0000

Timestamp Conversion: 2012-06-24 00:00:00 +0000

Prediction: 604800.000000

Which isn't the hard coded dates i used. Does anyone know why? Code is below:

NSString *timeStamp = @"20120620 19:23";//[[predictionData objectAtIndex:0 ] valueForKey:@"tmstmp"];
    NSString *predictionTime = @"20120620 19:30";// [[predictionData objectAtIndex:0 ] valueForKey:@"prdtm"];


    NSDateFormatter *ts = [[NSDateFormatter alloc] init];
    [ts setDateFormat:@"yyyyMMdd HH:dd"];
    NSDate *convertedTS = [ts dateFromString:timeStamp];

    NSDateFormatter *pt = [[NSDateFormatter alloc] init];
    [pt setDateFormat:@"yyyyMMdd HH:dd"];
    NSDate *convertedPT = [pt dateFromString:predictionTime];

    NSTimeInterval timeDifference = [convertedPT timeIntervalSinceDate:convertedTS];



    NSLog(@"Prediction Conversion: %@", [convertedPT description]);
    NSLog(@"Timestamp Conversion: %@", [convertedTS description]);

    NSLog(@"Prediction: %f", timeDifference);

Thanks!

Upvotes: 0

Views: 182

Answers (3)

Evan Mulawski
Evan Mulawski

Reputation: 55334

You formatter string is incorrect.

HH:dd

should be

HH:mm

In addition, you need to take the timezone into consideration. Without +XXXX specified, UTC is used by default. To set the timezone:

[ts setTimeZone:[NSTimeZone /*timezone*/]];

where /*timezone*/ is specified by the NSTimeZone class. There are many different ways of using a timezone (and many different timezones), so choose the one that is best for you.

Upvotes: 1

hypercrypt
hypercrypt

Reputation: 15376

You need to set the locale, set it to en_us_POSIX.

ts.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_us_POSIX"];

also, it should be HH:mm, not dd

Upvotes: 0

Perception
Perception

Reputation: 80593

You are using dd for your minutes instead of mm. This:

[ts setDateFormat:@"yyyyMMdd HH:dd"];

Should be this:

[ts setDateFormat:@"yyyyMMdd HH:mm"];

Upvotes: 1

Related Questions