我在stackoverflow上遇到了很多链接,并尝试实现代码以这种格式的时间戳转换2013-07-20T12:23:54.411+05:30到这种格式的 NSDate
2013 年 7 月 20 日(星期二)12:23:54 或 1 分钟前、2 天前格式。
我已经实现了以下代码。toDate 为 nil 即 date1 给出 nil 值。似乎 Xcode 对这个问题很讽刺
我的意思是,您认为该操作对于零 toDate 应该意味着什么?目前已经避免了一个例外。此投诉将报告其中一些错误,然后进一步的违规行为将简单地默默地执行 nil 导致的任何随机事情。
谁能告诉我哪里出错了?
NSDateFormatter *dateForm = [[NSDateFormatter alloc] init];
[dateForm setDateFormat:@"yyyy-mm-ddTHH:mm:ssssZ"];
[dateForm setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"GMT"]];
[dateForm setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];
NSCalendar *cal = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
[cal setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"GMT"]];
[cal setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];
NSDate *date1 = [dateForm dateFromString:string];
NSDate *date2 = [NSDate date];
unsigned int unitFlags = NSDayCalendarUnit|NSYearCalendarUnit|NSMonthCalendarUnit|NSHourCalendarUnit|NSMinuteCalendarUnit|NSSecondCalendarUnit;
// gets the difference between the current date and also the date and time in the timestamp of the data
NSDateComponents *diffComps = [cal components:unitFlags fromDate:date2 toDate:date1 options:0];
int year = ABS([diffComps year]);
int month = ABS([diffComps month]);
int day = ABS([diffComps day]);
int hour = ABS([diffComps hour]);
int minute = ABS([diffComps minute]);
int seconds = ABS([diffComps second]);
NSString *displayTime;
if (year == 0) {
if (month == 0) {
if (day == 0) {
if (hour == 0){
if (minute == 0) {
displayTime = [NSString stringWithFormat:@"about %d secs ago",seconds];
}
else {
displayTime = [NSString stringWithFormat:@"about %d mins ago",minute];
}
}
else {
displayTime = [NSString stringWithFormat:@"about %d hours ago",hour];
}
}
else {
displayTime = [NSString stringWithFormat:@"about %d days ago",day];
}
}
else {
displayTime = [NSString stringWithFormat:@"about %d months ago",month];
}
}
else {
displayTime = [NSString stringWithFormat:@"about %d years ago",year];
}
编辑:这适用于我在 appdelegate 中创建的字符串。但不是我在单例类中创建的字符串。