Objective C - create NSDate from two Strings

旧时模样 提交于 2019-12-13 03:22:43

问题


Short version: Is there a way to combine two NSDates (which can be formed from two different strings) into a single NSDate object?

Detail: In my app, there are two textfields where the user enters the day and the time, respectively (these are entered using a customised Date Picker). When I want to save the information in the database, the property of the object expects a single date, comprised of both the day and the time.

Here is how I set the strings:

 if ([mode isEqualToString:@"date"])
{
    self.dateFormat = [[NSDateFormatter alloc] init];
    [self.dateFormat setDateFormat:@"MM/dd/yy"];
    self.dateTextField.text = [self.dateFormat stringFromDate:date];
}
else if ([mode isEqualToString:@"time"])
{
    self.timeFormat = [[NSDateFormatter alloc] init];
    [self.timeFormat setDateFormat:@"hh:mm a"];
    self.timeTextField.text = [self.timeFormat stringFromDate:date];
}

where date is a NSDate passed in to the method. Now when I am trying to save the information in a different method, I have access to the strings and the date formats, so I am able to do

NSDate* tempDate = [self.dateFormat dateFromString: self.dateTextField.text];
NSDate* tempTime = [self.timeFormat dateFromString: self.timeTextField.text];

but that's as far as I can get... I'm not sure how to combine the dates together into a single entity. Would I combine the DateFormatter strings together somehow?

Thank you for your help :)


回答1:


Try this.

NSString *strTemp = [NSString stringwithFormat:@"%@ %@",self.dateTextField.text,self.timeTextField.text];

NSDateFormatter *dateFotmatter = [[[NSDateFormatter alloc] init] autorelease];

[self.dateFotmatter setDateFormat:@"MM/dd/yy hh:mm a"];

NSDate* tempDate = [self.dateFotmatter dateFromString:strTemp];

Hope it helps.

Enjoy coding.



来源:https://stackoverflow.com/questions/19321964/objective-c-create-nsdate-from-two-strings

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!