[英]Objective C - create NSDate from two Strings
Short version: Is there a way to combine two NSDates
(which can be formed from two different strings) into a single NSDate
object? 简短版:是否可以将两个
NSDates
(可以由两个不同的字符串组成)组合成一个NSDate
对象?
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. date
是传递给方法的NSDate
。 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?
我会以某种方式将DateFormatter字符串组合在一起吗?
Thank you for your help :) 谢谢您的帮助 :)
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. 享受编码。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.