繁体   English   中英

如何将NSString转换为NSDate?

[英]How to turn a NSString into NSDate?

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

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

进入NSDate?

unicode日期格式doc就在这里

另外,根据您的情况,您可以尝试这样做:

// 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部分放在单引号中,并检查unicode文档以获取确切的格式。 就我而言,我有类似的东西,我这样做:

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

再次,不完全相同,但你明白了。 另外,在字符串和nsdates之间来回转换时要小心时区。

在我的情况下,我再次使用:

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

你试过这个吗?

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

干杯

你可以查看TouchTime。

https://github.com/jheising/TouchTime

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

希望它有效,并享受!

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

“一个扩展Cocoa的NSDate类的类,带有一些便利功能。”

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

这是他们页面的一个例子:

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

暂无
暂无

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

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