Objective C - 从两个字符串创建 NSDate [英] Objective C - create NSDate from two Strings
问题描述
简短版本:有没有办法将两个 NSDates
(可以由两个不同的字符串组成)组合成一个 NSDate
对象?
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];
}
其中 date
是传递给方法的 NSDate
.现在,当我尝试以不同的方法保存信息时,我可以访问字符串和日期格式,因此我可以这样做
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];
但这是我所能得到的......我不知道如何将日期组合成一个实体.我会以某种方式将 DateFormatter 字符串组合在一起吗?
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?
感谢您的帮助:)
推荐答案
试试这个.
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];
希望有帮助.
享受编码.
这篇关于Objective C - 从两个字符串创建 NSDate的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!