2012-03-12 85 views
1

我希望能夠在我的表格的標題中乾淨地設置我的日期。以下是我的代碼:如何從NSFetchedResultsSectionInfo格式化日期?

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section 
{ 
id <NSFetchedResultsSectionInfo> sectionInfo = [[self.fetchedResultsController sections] objectAtIndex:section]; 
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init]; 
[dateFormatter setDateStyle:NSDateFormatterMediumStyle]; 
NSDate *date = [dateFormatter dateFromString:sectionInfo.name]; 
NSString *formattedDate = [dateFormatter stringFromDate:date]; 
NSLog(@"%@", formattedDate); 
return formattedDate; 
} 

使用此代碼,由於日期爲空,因此沒有節標題出現。出於某種原因,dateFromString無法將字符串sectionInfo.name轉換爲NSDate。有什麼建議麼?

+1

你的字符串'date'格式化到什麼程度? – 2012-03-12 22:21:42

+0

+1塞巴斯蒂安的問題。只是我猜他是指section的標題字符串 - sectionInfo.name的格式。如果coredata正確讀取所有內容,那麼唯一可能導致錯誤的是格式不匹配。 – makaron 2012-03-12 22:37:47

+0

嘿,我的部分標題上顯示的字符串是在窗體中:2012-03-12 07:00:00 +0000我試圖將其轉換爲2012年3月3日 – djblue2009 2012-03-12 22:56:45

回答

2

考慮到您的評論,如果您指出日期標題的格式爲2012-03-12 07:00:00 +0000,則可以確定問題出現在格式設置中。

NSDateFormatterMediumStyle的格式爲「1937年11月23日」 - 這是你的錯配:)

你必須使用這樣的:從格式的字符串

[dateFormatter setDateStyle:@"yyyy-dd-MM HH:mm:ss ZZZ"]; 

,以取得一個NSDate你有。那麼應該工作。

如果需要返回與NSDateFormatterMediumStyle格式的NSString,那麼你得到的NSDate後,纔可以將其應用到你的dateFormatter對象爲你做的事:

[dateFormatter setDateStyle:NSDateFormatterMediumStyle]; 

,然後用這個dateFormatter擺脫字符串日你有:

NSString *formattedDate = [dateFormatter stringFromDate:date]; 
+0

謝謝makaron!我做了一些編輯,但關鍵的洞察是,爲了獲取一個字符串並將其轉換爲日期,我必須將DateFormat設置爲字符串的初始格式,而不是我想要的格式。然後,它被轉換成我可以操縱其格式的日期。 – djblue2009 2012-03-13 21:08:13

0

鑑於沒有負載設置我的日期解析器和日期格式

@property(nonatomic, strong) NSDateFormatter *dateParser; 
@property(nonatomic, strong) NSDateFormatter *dateFormatter; 
@property(nonatomic, strong) NSDateFormatter *timeFormatter; 


- (void)viewDidLoad { 
    [super viewDidLoad]; 

    self.dateParser = [[NSDateFormatter alloc] init]; 
    self.dateFormatter = [[NSDateFormatter alloc] init]; 

    [self.dateParser setDateFormat:@"yyyy-MM-dd HH:mm:ss Z"]; 
    [self.dateFormatter setDateStyle:NSDateFormatterFullStyle]; 
    ...  
} 


- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section { 
    id <NSFetchedResultsSectionInfo> sectionInfo = [[self.fetchedResultsController sections] objectAtIndex:section]; 
    NSDate *date = [self.dateParser dateFromString:sectionInfo.name]; 
    return [self.dateFormatter stringFromDate:date]; 
}