簡體   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