Objective-C 时间跨度
在 C# 中,如果我想将字符串解析为日期和时间跨度,我会执行类似于以下操作的操作:
String input = "08:00";
DateTime time;
if (!DateTime.TryParse(input, out time))
{
// invalid input
return;
}
TimeSpan timeSpan = new TimeSpan(time.Hour, time.Minute, time.Second);
我的 Google-Fu 在找到将其转换为 Objective-C 的方法方面不太令人满意。
有什么建议么?
In C#, if I wanted to parse out a string into a date and timespan, I'd do something similar to the following:
String input = "08:00";
DateTime time;
if (!DateTime.TryParse(input, out time))
{
// invalid input
return;
}
TimeSpan timeSpan = new TimeSpan(time.Hour, time.Minute, time.Second);
My Google-Fu has been less than desirable in finding a way to convert this to Objective-C.
Any suggestions?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
Cocoa 日期和时间编程指南可能有助于寻找方法最适合您的需求。 我敢打赌 NSDateComponents 将特别令人感兴趣 - 您可以从
-[NSCalendar 组件:fromDate:]
方法。至于从字符串中获取日期,您可以尝试的一种方法是使用 NSDateFormatter,它具有
-dateFromString:
和-stringFromDate:
等方法来在 NSString 和 NSDate 表示形式之间进行转换。 您可以使用-setDateFormat:
指定用于解析的格式字符串。 一旦你有了一个 NSDate 对象,你也可以使用一个其-timeIntervalSince...
方法来获取 NSTimeInterval 这是一个双精度值,以秒为单位。The Date and Time Programming Guide for Cocoa will likely be helpful for finding an approach that best fits your needs. I'd bet that NSDateComponents will be of particular interest — you can obtain an instance of this class from the
-[NSCalendar components:fromDate:]
method.As far as getting the date from a string, one approach you could try is using NSDateFormatter, which has methods like
-dateFromString:
and-stringFromDate:
to convert between NSString and NSDate representations. You can use-setDateFormat:
to specify the format string to use for parsing. Once you have an NSDate object, you can also use one of its-timeIntervalSince...
methods to get an NSTimeInterval which is a double value, measured in seconds.