[英]How to format the layout of an NSDate without converting to NSString
我想更改將日期對象放入nsdictionary的方式當前,以以下格式輸入日期對象:
2014-04-22 17:28:47 +0000
但是我希望只輸入為
22-04-2014
我嘗試使用NSDateFormatter,但僅在將其放入字符串的地方使用過
NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
[formatter setDateFormat:@"dd-MM-yyyy"];
NSString *theDate = [formatter stringFromDate:date];
如何簡單地從yyyy-mm-dd hh:m:ss ????
更改布局yyyy-mm-dd hh:m:ss ????
到dd-mm-yyy
但將其保留為日期對象?
在與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;
}
此類是一個數據模型,您將使用該模型將數據存儲在數據庫中。 如果您沒有任何設置,但想嘗試測試搜索算法,則可以始終創建一個本地臨時手動容器,該容器將在程序運行時使用。
現在,您想使用Apple SQLITE數據庫還是使用Apple 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
搜索功能中的日期字符串的格式與您將日期保存在臨時數據庫中的格式相同。
好運哥們。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.