2012-04-13 95 views
1

我想我的約會從的NSString轉換成NSDate的使用下面的代碼IOS:字符串到日期轉換

NSDateFormatter *dateformatter = [[NSDateFormatter alloc]init]; 
[dateformatter setDateStyle:NSDateFormatterShortStyle]; 
[dateformatter setTimeStyle:NSDateFormatterNoStyle]; 
[dateformatter setDateFormat:@"dd/MM/yyyy"]; 
NSDate *myDate = [[NSDate alloc] init]; 

currMonth = 3; 
currYear = 2012; 
NSString *str = [NSString stringWithFormat:@"01/%2d/%d", currMonth, currYear]; 
str = [str stringByReplacingOccurrencesOfString:@" " withString:@"0"]; 
myDate = [dateformatter dateFromString:str]; 
NSLog(@"myStr: %@",str); 
NSLog(@"myMonth: %2d",currMonth); 
NSLog(@"myYear: %d",currYear); 
NSLog(@"myDate: %@",myDate); 

上面的代碼是給我錯誤的日期。任何人都可以幫忙嗎?

+0

哪個日期將給予?你能給個例子嗎? – Tobi 2012-04-13 09:23:51

+0

感謝大家。 – Nir 2012-04-13 10:07:01

回答

3

你的輸出是什麼?請記住,NSDate使用UTC。

2012-03-01 00:00:00 (GMT+1)2012-02-39 23:00:00 (UTC)

另一個祕訣:

%02格式的前導零的整數。

+0

感謝您的提示。我得到以下輸出myStr的:01/03/2012 myMonth:3 myYear:2012 指明MyDate:2012-02-29 18:30:00 +0000 – Nir 2012-04-13 09:34:03

+0

正如克里斯托弗所說,NSDate的對象存儲在UTC日期,因此當你使用'NSLog(@「myDate:%@」,myDate)得到對象描述;'它將以UTC打印。嘗試使用格式化程序輸出日期,我認爲一旦將其轉換爲當地時區,您期望的輸出就會出現。例如:'NSLog(@「myDate:%@」,[dateformatter stringFromDate:myDate]);' – 2012-04-13 09:45:09

0

嘗試

NSDateFormatter *dateformatter = [[NSDateFormatter alloc]init]; 
[dateformatter setDateStyle:NSDateFormatterShortStyle]; 
[dateformatter setTimeStyle:NSDateFormatterNoStyle]; 
[dateformatter setDateFormat:@"dd/MM/yyyy"]; 
NSDate *myDate = [[NSDate alloc] init]; 

int currMonth = 3; 
int currYear = 2012; 
NSString *str = [NSString stringWithFormat:@"01/%2d/%d", currMonth, currYear]; 
str = [str stringByReplacingOccurrencesOfString:@" " withString:@"0"]; 

//SET YOUT TIMEZONE HERE 
dateformatter.timeZone = [NSTimeZone timeZoneWithAbbreviation:@"PDT"]; 
myDate = [dateformatter dateFromString:str]; 
NSLog(@"myStr: %@",str); 
NSLog(@"myMonth: %2d",currMonth); 
NSLog(@"myYear: %d",currYear); 
NSLog(@"myDate: %@",myDate); 
+0

這會給myDate:2012-03-01 08:00:00 +0000 – TompaLompa 2012-04-13 09:38:16

1

試試這個:

-(NSDate *)dateFromString:(NSString *)string 
{ 
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init]; 
NSLocale *locale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US"]; 
[dateFormat setLocale:locale]; 
[dateFormat setDateFormat:@"yyyy-MM-dd HH:mm:ss"]; 
NSTimeInterval interval = 5 * 60 * 60; 

NSDate *date1 = [dateFormat dateFromString:string]; 
date1 = [date1 dateByAddingTimeInterval:interval]; 
if(!date1) date1= [NSDate date]; 
[dateFormat release]; 
[locale release]; 

return date1; 
} 

告訴我,如果它可以幫助U:]