2009-11-04 51 views
0
NSDateFormatter *inputFormatter = [[NSDateFormatter alloc] init]; 
[inputFormatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss"]; 
NSDate *formatterDate = [inputFormatter dateFromString:@"2009-11-03T21:02:34-08:00"]; 
[inputFormatter release]; 
NSDateFormatter *outputFormatter = [[NSDateFormatter alloc] init]; 
[outputFormatter setDateFormat:@"HH:mm 'on' yyyy/MM/dd"]; 
[outputFormatter setTimeStyle:NSDateFormatterShortStyle]; 
[outputFormatter setDateStyle:NSDateFormatterShortStyle]; 


NSString *newDateString = [outputFormatter stringFromDate:formatterDate]; 
NSLog(@"newDateString %@", newDateString); 

輸出日期的第一個和之後的時間如何解決這個問題?在短文體中解析時間和日期時NSDateFormatter中的錯誤

我想在很短的風格,比日

回答

1

當你設定的時間和日期的款式來顯示時間,你會覆蓋您手動設置日期格式。

試試這個:

NSDateFormatter *inputFormatter = [[NSDateFormatter alloc] init]; 
[inputFormatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss"]; 
NSDate *formatterDate = [inputFormatter dateFromString:@"2009-11-03T21:02:34-08:00"]; 
[inputFormatter release]; 
NSDateFormatter *outputFormatter = [[NSDateFormatter alloc] init]; 

//[outputFormatter setDateFormat:@"HH:mm 'on' yyyy/MM/dd"]; 
//[outputFormatter setTimeStyle:NSDateFormatterShortStyle]; 
//[outputFormatter setDateStyle:NSDateFormatterShortStyle]; 
//NSString *newDateString = [outputFormatter stringFromDate:formatterDate]; 

// format for time only 
[outputFormatter setTimeStyle:NSDateFormatterShortStyle]; 
[outputFormatter setDateStyle:NSDateFormatterNoStyle]; 

// get time 
NSString *newTimeString = [outputFormatter stringFromDate:formatterDate]; 

// format for date only 
[outputFormatter setTimeStyle:NSDateFormatterNoStyle]; 
[outputFormatter setDateStyle:NSDateFormatterShortStyle]; 

// get date and format with time 
NSString *newDateString = [NSString stringWithFormat:@"%@ on %@", newTimeString, [outputFormatter stringFromDate:formatterDate]]; 

NSLog(@"newDateString %@", newDateString); 
0

設置timeStyledateStyle意味着格式化忽略dateFormat您設定。如果你總是您的日期被格式化爲00:00 on 2009/11/04不論用戶的語言環境,你應該設置這樣的語言環境:

NSDateFormatter*outputFormatter = [[[NSDateFormatter alloc] init] autorelease]; 
NSLocale* locale = [[[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"] autorelease]; 
[outputFormatter setLocale:locale]; 
[outputFormatter setDateFormat:@"HH:mm 'on' yyyy/MM/dd"]; 

NSString* newDateString = [outputFormatter stringFromDate:formatterDate]; 

請注意,您應該在區域始終設置爲en_US_POSIX如果你處理機器讀取日期(例如ISO 8601),因爲某些語言環境會將'HH'變爲'hh',這可能會產生意想不到的結果。