[英]NSString to NSDate conversion using NSDateformatter
我有一個日期為2010-11-29T00:00:00 + 05:30的字符串,我想將其轉換為NSDate
。 我想將其轉換為2010年11月29日。 為此,我正在做類似的事情。
NSDateFormatter *df = [[NSDateFormatter alloc] init];
textForLabel = @"2010-11-29T00:00:00+05:30";
[df setDateFormat:@"yyyy-MM-dd"];
NSDate *myDate = [df dateFromString:textForLabel];
NSLog(@"date : %@",myDate);
但是輸出為空。
什么是2010-11-29T00:00:00 + 05:30的日期格式?
我沒有弄錯這里的地方。
首先,在時區中消除冒號,因為沒有用於“ +05:30”的時區格式標識符
textForLabel = [textForLabel
stringByReplacingCharactersInRange:NSMakeRange(21,1)
withString:@""];
然后,您將擁有以下字符串: 2010-11-29T00:00:00+0530
可以使用以下日期格式:
[df setDateFormat:@"yyyy:MM:dd'T'HH:mm:sszzz"];
textForLabel = 2010-11-29T00:00:00 + 05:30
那不是字符串。 考慮到缺少結尾的分號,我懷疑它是否還會編譯,但是如果這樣做的話,編譯器可能會將其解釋為表達式並將結果編號分配給textForLabel
。 要使其成為字符串,請執行以下操作:
textForLabel = @"2010-11-29T00:00:00+05:30";
嘗試這個,
NSDateFormatter *df = [[NSDateFormatter alloc] init];
textForLabel = @"2010-11-29T00:00:00+05:30";
NSArray *components = [textForLabel componentsSeperatedByString:@"T"];
[df setDateFormat:@"yyyy-MM-dd"];
NSDate *myDate = [df dateFromString:[components objectAtIndex:0]];
NSLog(@"date : %@",myDate);
這不是理想的方法,但是可以使用:)
-(NSDate *) getDateFor :(NSString *)ICSDateString
{
int strLen = [ICSDateString length];
NSString * subString1 = [ICSDateString substringWithRange:NSMakeRange(0, strLen - 1)];
NSLog(@"%d %d subString1 %@", strLen, subString1.length, subString1);
NSDateFormatter* df = [[NSDateFormatter alloc] init];
[df setDateFormat:@"yyyyMMdd'T'HHmmss'Z'"];
[df setLocale:[[[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"] autorelease]];
NSDate* parsedDate = [df dateFromString:subString1];
[df release];
NSLog(@"parsedDate %@", parsedDate);
return parsedDate;
}
想想,這是從ICS格式化日期獲取NSDate的正確方法。 請看此鏈接以供參考。 謝謝。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.