2014-04-20 22 views
0

我期待改变日期对象被放入一个NSDictionary 目前,该日期对象被下面的格式输入方式:如何格式化一个NSDate的布局,无须转换为NSString的

2014-04-22 17:28:47 +0000 

不过,我想在那里它置入一个字符串

它只被输入为

22-04-2014 

我使用NSDateFormatter尝试,但我只用它

我该如何实现将布局从yyyy-mm-dd hh:m:ss ????更改为dd-mm-yyy,但将其作为日期对象进行维护?

+2

日期格式存储日期对象,除非您想以可视方式显示日期格式,否则无需调整日期格式,这就是格式化程序将其设置应用于字符串的原因,以便您可以按自己喜欢的方式表示它。 – Pavan

+0

这是否意味着当试图找到一个对象时会出现问题?如果我试图找到22-04-2014这将是相当简单的,但如果没有格式化它的方式,这意味着有一个时间元素的日期对象,我不得不参考“22-04-2014 19:09:32“例如..? – user3547147

+0

我猜我也可以改变它首先输入到词典中的方式,而不会妨碍我所需要的... – user3547147

回答

1

经与OP讨论后得出结论,以下内容将取得预期效果。

创建一个新的类,它看起来像这样

//FoodItem . h 

NSString *foodItemName; 
NSString *foodItemDate; 
//You can add more stuff like calorie intake etc 

//Have a custom init method 
-(id)initNewFoodItemName:(NSString*)name withDate:(NSString*)dateInput; 


//THEN IN YOUR 
//FoodItem.m 

//Make sure you Synthesise the properties above. 
-(id)initNewFoodItemName:(NSString*)name withDate:(NSString*)dateInput{ 
    if (self = [super init]) { 
     self.foodItemName = name; 
     self.foodItemDate = dateInput; 
    } 
    return self; 
} 

此类是将用于在数据库中存储数据的数据模型。 如果您没有一个设置,但想要测试您的搜索算法以获得乐趣,您可以随时创建一个本地临时手动容器,该容器将在您的程序的运行时间内运行。

现在是否要使用苹果SQLITE数据库或使用苹果Core Data数据库将其存储在临时数据库或本地数据库中;你可以做这样的东西真棒:

NSMutableArray *temporaryDB = [[NSMutableArray alloc] init]; 
[temporaryDB addObject:[[FoodItem alloc] initNewFoodItemName:@"Banana" withDate:@"2014-04-20"]]; 
[temporaryDB addObject:[[FoodItem alloc] initNewFoodItemName:@"Egg" withDate:@"2014-03-20"]]; 
[temporaryDB addObject:[[FoodItem alloc] initNewFoodItemName:@"chocolate" withDate:@"2014-04-18"]]; 

然后,当用户选择特定的日期,因为你想显示他们已经对特定日期吃过的所有食物,你可以提取从日期选择器日期,使用日期格式将其转换成字符串,然后通过temporaryDB阵列搜索,看是否有对象得到,如果日期的比赛回来,就像这样:

-(NSMutableArray*)searchForAllFoodItemsOnACertainDate:(NSString*)searchDate{ 
    NSMutableArray *returnedResults = [[NSMutableArray alloc] init]; 
    for(int i = 0; i < [temporaryDB count]; i++){ 

     FoodItem *currentFoodItem = [temporary objectAtIndex:i]; 

     //if a date is found in the temporary DB then store it into the returnedResults array 
     if([currentFoodItem.foodItemDate isEqualToString:searchDate]){ 

      [returnedResults addObject:currentFoodItem]; 
     } 
    } 
    //In the end you will have a all the food items that were eaten on the day or if none was eaten, then an empty array will be returned with a size of 0 

    return returnedResults; 
} 

然后其他地方的程序一旦用户选择一个日期,然后点击done按钮,就可以调用搜索功能,如

NSMutableArray *foodItemsEatenOnChosenDate = [self searchForAllFoodItemsOnACertainDate:dateFromDatePicker]; 


if([foodItemsEatenOnChosenDate count] > 0){ 
    //These were the food items eaten on that date the user selected from the date picker 
} 
else{ 
    //let the user know that they didnt record any food items on that day 
} 

请注意以下事项

你必须确保你送入foodItemsEatenOnChosenDate搜索功能日期字符串是你在你的临时数据库中保存的日期相同的格式。

Goodluck哥们。