ios 如何正确使用 NSTimeInterval?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13309376/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to use NSTimeInterval properly?
提问by Joaocdn
I'm new to Xcode and I have the following problem:
我是 Xcode 的新手,我有以下问题:
I want a method that gives me the time that as passed since a given date till now. If it was 2 years ago I want to return a string "2 years ago", but if it was 5 minutes ago I want it to return a string with "5 minutes ago".
我想要一种方法,它可以为我提供从给定日期到现在为止的时间。如果是 2 年前,我想返回一个字符串“2 年前”,但如果是 5 分钟前,我希望它返回一个带有“5 分钟前”的字符串。
I've already checked NSTimeInterval and NSDateFormatter but I couldn't find a way to make it work.
我已经检查了 NSTimeInterval 和 NSDateFormatter 但我找不到让它工作的方法。
回答by Rok Jarc
Just to get you started...
只是为了让你开始...
You would create a reference date like this:
您将创建一个这样的参考日期:
NSCalendar *gregorian = [[NSCalendar alloc]
initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *dateComponents = [[NSDateComponents alloc] init];
dateComponents.year = 2012;
dateComponents.month = 1;
dateComponents.day = 1;
dateComponents.hour = 0;
dateComponents.minute = 0;
dateComponents.second = 0;
NSDate *referenceDate = [gregorian dateFromComponents: dateComponents];
Current date can be obtained like this:
当前日期可以这样获得:
NSDate *now = [NSDate date];
Time interval is in seconds, so...
时间间隔以秒为单位,所以...
NSTimeInterval interval = [now timeIntervalSinceDate:referenceDate];
NSLog (@"reference date was %.0f seconds ago", interval);
I'm sure you'll be able to figure it out on yourself from here on...
我相信从现在开始你就能自己弄清楚了......
This answermight help you out.
这个答案或许能帮到你。
回答by vikingosegundo
Thank you, I was wondering if there is an easier way of doing it without having so many lines of code.
谢谢,我想知道是否有一种更简单的方法可以在没有这么多代码行的情况下做到这一点。
You could create the reference date like this:
您可以像这样创建参考日期:
NSDate *referenceDate = [NSDate date];
[[NSCalendar currentCalendar] rangeOfUnit:NSYearCalendarUnit
startDate:&referenceDate
interval:NULL
forDate:referenceDate];
or you try this: https://github.com/billgarrison/SORelativeDateTransformer
或者你试试这个:https: //github.com/billgarrison/SORelativeDateTransformer