【发布时间】:2016-01-20 07:31:07
【问题描述】:
我想在 iOS 中获得几小时前、几天前的时间/日期格式。但我得到了错误的数据。例如,如果时间是:
2015-10-21 03:43:20
然后根据下面的代码显示 6 小时前。我在 php 中使用 Now() 函数来保存时间/日期,那么如何显示不同国家/地区的确切时间?
+(NSString*)HourCalculation:(NSString*)PostDate
{
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
NSTimeZone *gmt = [NSTimeZone timeZoneWithAbbreviation:@"GMT"];
[dateFormat setTimeZone:gmt];
NSDate *ExpDate = [dateFormat dateFromString:PostDate];
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *components = [calendar components:(NSDayCalendarUnit|NSWeekCalendarUnit|NSMonthCalendarUnit|NSYearCalendarUnit|NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit) fromDate:ExpDate toDate:[NSDate date] options:0];
NSString *time;
if(components.year!=0)
{
if(components.year==1)
{
time=[NSString stringWithFormat:@"%ld year",(long)components.year];
}
else
{
time=[NSString stringWithFormat:@"%ld years",(long)components.year];
}
}
else if(components.month!=0)
{
if(components.month==1)
{
time=[NSString stringWithFormat:@"%ld month",(long)components.month];
}
else
{
time=[NSString stringWithFormat:@"%ld months",(long)components.month];
}
}
else if(components.week!=0)
{
if(components.week==1)
{
time=[NSString stringWithFormat:@"%ld week",(long)components.week];
}
else
{
time=[NSString stringWithFormat:@"%ld weeks",(long)components.week];
}
}
else if(components.day!=0)
{
if(components.day==1)
{
time=[NSString stringWithFormat:@"%ld day",(long)components.day];
}
else
{
time=[NSString stringWithFormat:@"%ld days",(long)components.day];
}
}
else if(components.hour!=0)
{
if(components.hour==1)
{
time=[NSString stringWithFormat:@"%ld hour",(long)components.hour];
}
else
{
time=[NSString stringWithFormat:@"%ld hours",(long)components.hour];
}
}
else if(components.minute!=0)
{
if(components.minute==1)
{
time=[NSString stringWithFormat:@"%ld min",(long)components.minute];
}
else
{
time=[NSString stringWithFormat:@"%ld mins",(long)components.minute];
}
}
else if(components.second>=0)
{
if(components.second==0)
{
time=[NSString stringWithFormat:@"1 sec"];
}
else
{
time=[NSString stringWithFormat:@"%ld secs",(long)components.second];
}
}
return [NSString stringWithFormat:@"%@ ago",time];
}
【问题讨论】:
-
你搜索了吗?我确定以前有人问过这个问题。
标签: ios objective-c timezone