简体   繁体   English

无法将NSString转换为NSDate

[英]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: 运行此代码后,我从NSLogs获得以下输出:

Prediction Conversion: 2012-07-01 00:00:00 +0000 预测转换:2012-07-01 00:00:00 +0000

Timestamp Conversion: 2012-06-24 00:00:00 +0000 时间戳转换:2012-06-24 00:00:00 +0000

Prediction: 604800.000000 预测: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! 谢谢!

You are using dd for your minutes instead of mm. 您使用dd代替mm而不是mm。 This: 这个:

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

Should be this: 应该是这样的:

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

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. 如果未指定+XXXX ,则默认使用UTC。 To set the timezone: 设置时区:

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

where /*timezone*/ is specified by the NSTimeZone class. 其中/*timezone*/NSTimeZone类指定。 There are many different ways of using a timezone (and many different timezones), so choose the one that is best for you. 使用时区(以及许多不同的时区)有许多不同的方法,因此请选择最适合您的方式。

You need to set the locale, set it to en_us_POSIX . 您需要设置区域设置,将其设置为en_us_POSIX

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

also, it should be HH:mm , not dd 它也应该是HH:mm ,而不是dd

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM