如何从日期字符串获取经过的秒数?

发布于 2024-09-27 00:28:00 字数 122 浏览 2 评论 0原文

在 Objective-C 中,我想确定日期字符串所经过的秒数,例如:“Sat, 09 Oct 2010 06:14:50 +0000”

我该如何执行此操作?我迷失在 NSDateFormatter 的复杂描述中。

In objective-C, I want to determine the seconds elapsed from a date string such as: "Sat, 09 Oct 2010 06:14:50 +0000"

How do I do this? I got lost in the convoluted descriptions of NSDateFormatter.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(1

马蹄踏│碎落叶 2024-10-04 00:28:00

此示例给出了自当前时间以来经过的秒数:

NSString *dateString = @"Sat, 09 Oct 2010 18:14:50 +0000";

NSDateFormatter *df = [[NSDateFormatter alloc] init];
[df setDateFormat:@"EEE, dd MMM yyyy HH:mm:ss Z"];

NSLocale *usLocale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US"];
[df setLocale:usLocale];
[usLocale release];

NSDate *date = [df dateFromString:dateString];
[df release];

NSTimeInterval secondsSinceNow = [date timeIntervalSinceNow];

NSLog(@"date = %@", date);
NSLog(@"secondsSinceNow = %f", secondsSinceNow);

请注意,如果手机所在区域不是英语,则转换为日期将会失败,因为“Sat”和“Oct”在另一种语言中可能表示不同的意思。您可以在 dateFormatter 上强制使用区域设置来避免这种情况。

可以在此处找到用于日期格式的字符。

This example gives seconds elapsed since current time:

NSString *dateString = @"Sat, 09 Oct 2010 18:14:50 +0000";

NSDateFormatter *df = [[NSDateFormatter alloc] init];
[df setDateFormat:@"EEE, dd MMM yyyy HH:mm:ss Z"];

NSLocale *usLocale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US"];
[df setLocale:usLocale];
[usLocale release];

NSDate *date = [df dateFromString:dateString];
[df release];

NSTimeInterval secondsSinceNow = [date timeIntervalSinceNow];

NSLog(@"date = %@", date);
NSLog(@"secondsSinceNow = %f", secondsSinceNow);

Note that if the phone's region is not English-speaking, the conversion to date will fail since "Sat" and "Oct" may not mean the same thing in another language. You can force a locale on the dateFormatter to avoid this.

Characters to use in date formatting can be found here.

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