2012-07-16 54 views
1

我試圖用時間將NSString轉換爲NSDate。這是我現在正在做的:如何將NSString隨時間轉換爲NSDate?

NSString *myDateIs= @"2012-07-14 11:30:40 AM "; 
NSDateFormatter* startTimeFormat = [[NSDateFormatter alloc] init]; 
[startTimeFormat setDateFormat:@"YYYY-MM-dd hh:mm:ss a "]; 
NSDate*newStartTime = [startTimeFormat dateFromString:myDateIs]; 

輸出是2012-07-14 06:00:40 +0000。日期是正確的,但時間不正確。 我如何獲得正確的時間? 謝謝。

+1

使用此 NSString * myDateIs = @「2012-07-14 11:30:40 AM」; NSDateFormatter * startTimeFormat = [[NSDateFormatter alloc] init]; [startTimeFormat setDateFormat:@「YYYY-MM-dd hh:mm:ss a」]; [startTimeFormat setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@「GMT」]]; NSDate * newStartTime = [startTimeFormat dateFromString:myDateIs]; – 2012-07-16 08:01:47

+0

謝謝..現在它的工作正常... :) – Mani 2012-07-16 08:17:46

回答

2

你得到的時間是格林威治標準時間將它轉換成當地時間。

NSDateFormatter* local = [[[NSDateFormatter alloc] init] autorelease];   
[local setTimeZone:[NSTimeZone timeZoneWithName:@"EST"]]; 
[local setDateFormat:@"YYYY-MM-dd hh:mm:ss a"]; 

NSString* localSTR = [local stringFromDate: newStartTime]; 
1

時區。 NSDate將以GMT格式存儲時間。但是,您當地的時區可能完全不同。

1

您需要設置時區。

NSString *myDateIs= @"2012-07-14 11:30:40 AM "; 
NSDateFormatter* startTimeFormat = [[NSDateFormatter alloc] init]; 
startTimeFormat.timeZone=[NSTimeZone timeZoneWithName:@"UTC"]; 
[startTimeFormat setDateFormat:@"YYYY-MM-dd hh:mm:ss a"]; 
NSDate*newStartTime = [startTimeFormat dateFromString:myDateIs]; 
NSLog(@"%@", newStartTime); 

輸出:

2012-07-14 11:30:40 +0000 
1

這人會爲你工作:

[startTimeFormat setDateFormat:@"YYYY-MM-dd hh:mm:ss aa"]; 
[startTimeFormat setTimeZone:[NSTimeZone timeZoneWithName:@"UTC"]]; 

您在DATEFORMAT錯過的和必須設置時區。