一、在.h文件code
#import <Foundation/Foundation.h> typedef enum{ QHIntTypeRound = 0, //四捨五入 QHIntTypeCeil = 1, //向上取值 QHIntTypeFloor = 2, //向下取值 }QHIntType; @interface NSObject (timeStamp) + (NSString *)timechange:(NSString *)timeStr withFormat:(NSString *)format; + (NSString *)saveLength:(NSInteger)length andOldStr:(NSString *)str andType:(QHIntType)qhType; @end
二、在.m文件component
#import "NSObject+timeStamp.h" @implementation NSObject (timeStamp) + (NSString *)timechange:(NSString *)timeStr withFormat:(NSString *)format { if (timeStr.length>9) { NSTimeInterval time =[[timeStr substringToIndex:10] doubleValue]; NSDate *detaildate=[NSDate dateWithTimeIntervalSince1970:time]; //實例化一個NSDateFormatter對象 NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; //設定時間格式,這裏能夠設置成本身須要的格式 [dateFormatter setDateFormat:format]; NSString *currentDateStr = [dateFormatter stringFromDate: detaildate]; return currentDateStr; }else { NSTimeInterval time =[timeStr doubleValue]; NSDate *detaildate=[NSDate dateWithTimeIntervalSince1970:time]; //實例化一個NSDateFormatter對象 NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; //設定時間格式,這裏能夠設置成本身須要的格式 [dateFormatter setDateFormat:format]; NSString *currentDateStr = [dateFormatter stringFromDate: detaildate]; if (timeStr.length<1) { return @""; } return currentDateStr; // return QHLocalizedString(@"CurrencyExchangeCommissionNoNet", nil); } } + (NSString *)saveLength:(NSInteger)length andOldStr:(NSString *)str andType:(QHIntType)qhType{ if (!str) { return @""; } NSString *resultStr; NSArray *array = [str componentsSeparatedByString:@"."]; if (array.count >1) { NSString *firstt = array[0]; NSString *second = array[1]; if (second.length > length) { NSRange range = {length,1}; NSString *round = [second substringWithRange:range]; NSString *newStr = [second substringToIndex:length]; switch (qhType) { case QHIntTypeRound: { if ([round intValue]>length) { newStr = [NSString stringWithFormat:@"%@",@([newStr intValue]+1)]; } } break; case QHIntTypeCeil: { newStr = [NSString stringWithFormat:@"%@",@([newStr intValue]+1)]; } break; case QHIntTypeFloor:{ } default: break; } resultStr = [NSString stringWithFormat:@"%@.%@",firstt,newStr]; return resultStr ; }else{ return str; } }else{ return str; } } @end
三、說明:第一方法是將時間戳轉換成指定時間格式,第二方法是將傳入的數值保留指定小數後進行四捨五入、向上取值、向下取值等操做。orm