2011-06-01 85 views
2

我在我的应用程序中有一个计时器。当我点击退出buton时,计时器停止并以01:15:55的格式将值存储到字符串中。我有一个数组来存储这个字符串对象。如何在没有日期的情况下在NSDate中存储时间?

我想要的是,现在我想通过比较显示这些值。所以我想首先我必须将字符串转换为NSDate,但我只有时间格式,不想存储日期。

我该如何完成这项任务?任何建议?

编辑:代码

NSInteger secondsSinceStart = (NSInteger)[[NSDate date] timeIntervalSinceDate:sDate]; // sDate = when app get started 

myAppDelegate.seconds = secondsSinceStart % 60; 
myAppDelegate.minutes = (secondsSinceStart/60) % 60; 
myAppDelegate.hours = secondsSinceStart/(60 * 60); 
NSString *result = nil; 

if (myAppDelegate.hours > 0) 
{ 
    result = [NSString stringWithFormat:@"%02d:%02d:%02d", myAppDelegate.hours, myAppDelegate.minutes, myAppDelegate.seconds]; 
} 
else 
{ 
    result = [NSString stringWithFormat:@"%02d:%02d", myAppDelegate.minutes, myAppDelegate.seconds];   
} 

NSString *tempDateString = [NSString stringWithFormat:@"%d:%d:%d",[myAppDelegate hours],[myAppDelegate minutes],[mogsApp seconds]]; 

现在我想tempDateString转换成NSDate的,所以我可以用类似的比较对象。可能吗 ?

谢谢...

回答

4

听起来像一个NSTimeInterval可能更合适。这只是一个浮点值,表示秒数(包括小数秒)。您可以使用一些简单的除法和余数运算手动将这样的值格式化为任何想要的字符串格式。 (NSDate将自给定日期或其他日期起给出时间间隔,如果要使用这些值来获取值)。如果需要,可以将NSTimeIntervals作为字符串存储。

+0

雅我通过简单的划分和余数得到秒,分和小时。我得到字符串像0:0:9现在如何将此字符串转换为NSDate,以便我可以比较它? – Maulik 2011-06-01 06:37:28

+0

@Maulik:使用[NSScanner](http://developer.apple.com/library/ios/#documentation/Cocoa/Reference/Foundation/Classes/NSScanner_Class/Reference/Reference.html)解析字符串并将其转换到NSTimeInterval(这只是一个浮动,BTW)。想知道如何做到这一点,看看这个问题[如何将时间值的NSString表示转换为包含小时和分钟的两个NSInteger?](http://stackoverflow.com/questions/3432260/how-可以-I-转换-A-的NSString-表示对的一 - 时间 - 值 - 到 - 双nsintegers)。 – DarkDust 2011-06-01 06:39:48

+0

@darkDust:我只想做一下这个过程。当我准备好秒钟,分钟和小时。我想知道我可以将它转换成NSDate而不插入日期吗? – Maulik 2011-06-01 06:49:49

2

NSDateComponents当只存储部分日期/时间(或时间跨度)时总是一个不错的选择。

它还使您可以通过NSCalendar轻松访问时间管理方法。然后(与使用NSTimeInterval不同),您不必自行设置任何数学计算,它将全部自动进行本地化。

相关问题