【问题标题】:How to turn a NSString into NSDate?如何将 NSString 变成 NSDate?
【发布时间】:2011-06-08 11:46:11
【问题描述】:

我一直在绞尽脑汁没有运气。有人可以告诉我如何转换这个字符串:

“2011-01-13T17:00:00+11:00”

进入 NSDate?

【问题讨论】:

标签: objective-c xcode nsstring nsdate nsdateformatter


【解决方案1】:

你试过了吗

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
NSDate *dateT = [dateFormatter dateFromString:str];

干杯

【讨论】:

  • 嗨,是的,我有这个 NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; NSDate *dateT = [dateFormatter dateFromString:@"2011-01-13T17:00:00+11:00"]; NSLog(@"日期来自字符串:%@", dateT);这将返回 (null)
【解决方案2】:

将 T 部分放在单引号中,并检查 unicode 文档的确切格式。就我而言,我有类似的东西,我这样做:

NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
        [dateFormat setDateFormat:@"YYYY-MM-dd'T'HH:mm:ss.SSS"];

同样,不完全相同,但你明白了。此外,在字符串和 nsdate 之间来回转换时要注意时区。

再次,在我的例子中,我使用:

[dateFormat setTimeZone:[NSTimeZone timeZoneWithName:@"America/New_York"]];

【讨论】:

  • 嗨,我正在设置 [NSTimeZone systemTimeZone] 这是正确的区域。以下仍然返回null血腥的东西! [dateFormatter setDateFormat:@"yyyy-MM-dd'T'hh:mm:ssSSS"];
  • 那是我的代码,你需要为你的代码做类似的事情。再次检查 UNICODE 文档。
【解决方案3】:

unicode 日期格式文档为here

另外,根据你的情况,你可以试试这个:

// original string
NSString *str = [NSString stringWithFormat:@"2011-01-13T17:00:00+11:00"];

// convert to date
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
// ignore +11 and use timezone name instead of seconds from gmt
[dateFormat setDateFormat:@"YYYY-MM-dd'T'HH:mm:ss'+11:00'"];
[dateFormat setTimeZone:[NSTimeZone timeZoneWithName:@"Australia/Melbourne"]];
NSDate *dte = [dateFormat dateFromString:str];
NSLog(@"Date: %@", dte);

// back to string
NSDateFormatter *dateFormat2 = [[NSDateFormatter alloc] init];
[dateFormat2 setDateFormat:@"YYYY-MM-dd'T'HH:mm:ssZZZ"];
[dateFormat2 setTimeZone:[NSTimeZone timeZoneWithName:@"Australia/Melbourne"]];
NSString *dateString = [dateFormat2 stringFromDate:dte];
NSLog(@"DateString: %@", dateString);

[dateFormat release];
    [dateFormat2 release];

希望这会有所帮助。

【讨论】:

  • 谢谢你这是完美的。单引号中的时区不是预期的,而是修复它的原因:)
  • 无法找出中间的“T”。所以这有帮助。谢谢!
【解决方案4】:

您可以查看 TouchTime。

https://github.com/jheising/TouchTime.

它是 Cocoa 和 iOS 5.4 中 PHP 中令人敬畏的 strtotime 函数的直接端口。它将接受几乎任意格式的日期或时间字符串并将其转换为 NSDate。

希望它有效,并享受!

【讨论】:

    【解决方案5】:

    尝试使用这个启用了 cocoapods 的项目。可能还需要许多附加功能。

    “使用一些便利功能扩展 Cocoa 的 NSDate 类的类别。”

    https://github.com/billymeltdown/nsdate-helper

    这是他们页面中的一个示例:

    NSDate *date = [NSDate dateFromString:@"2009-03-01 12:15:23"];
    

    【讨论】:

    • 另外,现在主要搜索 cocoapods 上的实用程序。这是关于 NSDate 的查询。 cocoapods.org/?q=NSDate
    猜你喜欢
    • 2010-12-19
    • 1970-01-01
    • 1970-01-01
    • 2014-12-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-31
    相关资源
    最近更新 更多