从像1290529723这样的unix时间戳开始,我将如何(假设gmt)获取有关它的信息:
Starting with a unix timestamp like 1290529723, how would I (assuming gmt) get the information on whether it is:
-
今天(如果是,现在几点)
today (if so, what time)
过去七天(如果是,哪一天......周一,等等? )
in the last seven days (if so, which day ... mon, tues etc?)
我需要这个消息列表,比如iPhone的Mail应用程序,其中日期/时间相对于当前日期和时间显示,如下所示:
I need this for a list of messages like the iPhone's Mail app, where date/times are shown relative to the current date and time, like so:
15:45 Yesterday Sunday Saturday 10/10/10等
推荐答案
我使用这个方法将unix时间戳更改为一个可读的相对字符串。可能在新的一年的前几天没有正常工作,但希望你太过于注意。
I made this method to change the unix time stamp into a nice readable, relative string. Probably doesn't work properly in the first few days of a new year, but hopefully you should be too hungover to notice.
-(NSString *)relativeTime:(int)datetimestamp { NSDate *aDate = [NSDate dateWithTimeIntervalSince1970:datetimestamp]; NSCalendar *calendar = [NSCalendar currentCalendar]; unsigned int unitFlags = NSYearCalendarUnit|NSMonthCalendarUnit|NSWeekCalendarUnit|NSWeekdayOrdinalCalendarUnit|NSWeekdayCalendarUnit|NSDayCalendarUnit|NSHourCalendarUnit|NSMinuteCalendarUnit; NSDateComponents *messageDateComponents = [calendar components:unitFlags fromDate:aDate]; NSDateComponents *todayDateComponents = [calendar components:unitFlags fromDate:[NSDate date]]; NSUInteger dayOfYearForMessage = [calendar ordinalityOfUnit:NSDayCalendarUnit inUnit:NSYearCalendarUnit forDate:aDate]; NSUInteger dayOfYearForToday = [calendar ordinalityOfUnit:NSDayCalendarUnit inUnit:NSYearCalendarUnit forDate:[NSDate date]]; NSString *dateString; if ([messageDateComponents year] == [todayDateComponents year] && [messageDateComponents month] == [todayDateComponents month] && [messageDateComponents day] == [todayDateComponents day]) { dateString = [NSString stringWithFormat:@"%02d:%02d", [messageDateComponents hour], [messageDateComponents minute]]; } else if ([messageDateComponents year] == [todayDateComponents year] && dayOfYearForMessage == (dayOfYearForToday-1)) { dateString = @"Yesterday"; } else if ([messageDateComponents year] == [todayDateComponents year] && dayOfYearForMessage > (dayOfYearForToday-6)) { NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; [dateFormatter setDateFormat:@"EEEE"]; dateString = [dateFormatter stringFromDate:aDate]; [dateFormatter release]; } else { NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; [dateFormatter setDateFormat:@"yy"]; dateString = [NSString stringWithFormat:@"%02d/%02d/%@", [messageDateComponents day], [messageDateComponents month], [dateFormatter stringFromDate:aDate]]; [dateFormatter release]; } return dateString; }更多推荐
从unix时间戳获取人类可读的相对时间和日期?
发布评论