问题
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