Objective-C 时间跨度

发布于 2024-07-30 01:47:00 字数 336 浏览 1 评论 0原文

在 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

萌︼了一个春 2024-08-06 01:47:00

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文