iphone - 无法从字符串转换日期

标签 iphone objective-c ios xcode

我正在做一个应用程序,我正在使用以下链接 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/

相关文章:

iphone - 如何更改圆角矩形 UIbutton 背景颜色

iphone - 使 UITextView 全屏显示

iphone - iOS 5 中的 Twitter 用户 ID

objective-c - UIImagePickerController 自定义叠加预览拍摄的照片

iphone - 如何使用给定的@ 2x的ASIHTTPRequest填充UIImage View ?

javascript - 无论如何要在 iPad 上加载页面后用 javascript 删除所有 <a href=> 标签?

iphone - 在 iPhone 中将事件添加到默认日历时出错

objective-c - cocoa 网页 View : searchFor:direction:caseSensitive:

ios - 使用 Phonegap 显示最近捕获的图像

iphone - 如何检测完整的 body ,如手、腿?