我正在做一个应用程序,我正在使用以下链接 http://iosdevelopertips.com/cocoa/date-formatters-examples-take-3.html从字符串转换日期。
我按照上面的教程链接使用下面的代码。当我 NSlog
PresentDateTime
它给出 20120111 13:03:49.263+05:30。
所以我正在采用这种格式并希望转换为“EEEE MMMM d, YYYY h:mm a, zzz
”的格式。
当我将其分配给变量时这样做
NSString *today = presentDateTime;
当我 NSLog
Datestring
我得到结果 NULL
我能知道我哪里出错了吗?请通过建议要进行的更改来帮助我解决此问题
//代码
-(NSString *)DateFormat:(NSString *) presentDateTime
{
presentDateTime = [presentDateTime stringByReplacingOccurrencesOfString:@"T" withString:@" "];
presentDateTime = [presentDateTime stringByReplacingOccurrencesOfString:@" +" withString:@"+"];
presentDateTime = [presentDateTime stringByReplacingOccurrencesOfString:@"-" withString:@""];
NSLog(@"Present date::::%@",presentDateTime);
NSString *today = presentDateTime;
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:@"yyyyMMdd HH:mm:ss:SSSZZZ"];
NSDate *date = [dateFormat dateFromString:today];
[dateFormat setDateFormat:@"EEEE MMMM d, YYYY h:mm a, zzz"];
NSString *dateString = [dateFormat stringFromDate:date];
[dateFormat release];
NSLog(@"dateString:::Date>>>>:%@::::\n%@",dateString, presentDateTime);
return dateString;
最佳答案
您用于解析日期的日期格式模式错误/不完整。对于字符串 20120111 13:03:49.263+05:30
,格式将为 YYYYMMdd HH:mm:ss.SSSZZZ
。参见 this table用于格式字符串模式。
编辑:在尝试代码之后,结果是 NSDateParser
在时区 +05:30
上阻塞。它需要 +0530
,没有冒号。删除方法如下:
NSString *today = @"20120111 13:03:49.263+05:30";
NSRange colon = [today rangeOfString:@":" options:NSBackwardsSearch];
if (colon.location != NSNotFound) {
today = [today stringByReplacingCharactersInRange:colon withString:@""];
}
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:@"YYYYMMdd HH:mm:ss.SSSZZZ"];
NSDate *date = [dateFormat dateFromString:today];
NSLog(@"%@", date);
关于iphone - 无法从字符串转换日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8846460/