- 服務(wù)端接口下發(fā)的時(shí)間字符串 是UTC時(shí)間毫深,但app顯示的時(shí)候肯定需要進(jìn)行轉(zhuǎn)換成本地時(shí)區(qū)(中國(guó)北京)的時(shí)間字符串扇商,以下是我進(jìn)行處理的過(guò)程:
NSDictionary *dic = @{@"create_time":@"2017-10-25 02:07:39"};
NSDateFormatter *format = [[NSDateFormatter alloc] init];
format.dateFormat = @"yyyy-MM-dd HH:mm:ss";
NSTimeZone *sourceTimeZone = [NSTimeZone timeZoneWithName:@"UTC"];
//NSTimeZone *sourceTimeZone = [NSTimeZone timeZoneWithAbbreviation:@"UTC"];
format.timeZone = sourceTimeZone;
NSDate *createDate = [format dateFromString:dic[@"create_time"]];
NSTimeZone *desTimeZone = [NSTimeZone localTimeZone];
format.timeZone = desTimeZone;
NSString *localStr = [format stringFromDate:createDate];
NSLog(@"%@", localStr); //2017-10-25 10:07:39
NSCharacterSet *charSet = [NSCharacterSet characterSetWithCharactersInString:@" -:"];
NSArray *createTimeArr = [localStr componentsSeparatedByCharactersInSet:charSet];
- 為了防止createTimeArr直接取值時(shí)發(fā)生異常,將createTimeArr存放在一個(gè)TimeFormatModel類(lèi)中冤竹,類(lèi)的定義如下:
@interface LTTimeFormatModel : NSObject
@property (nonatomic, strong) NSString *year;
@property (nonatomic, strong) NSString *month;
@property (nonatomic, strong) NSString *day;
@property (nonatomic, strong) NSString *hour;
@property (nonatomic, strong) NSString *minute;
@property (nonatomic, strong) NSString *second;
@property (nonatomic, strong) NSString *timeStr;
- (instancetype)initWithArray:(NSArray *)arr timeStr:(NSString *)timeStr;
@end
@implementation LTTimeFormatModel
- (instancetype)initWithArray:(NSArray *)arr timeStr:(NSString *)timeStr{
if (self = [super init]) {
if (arr && arr.count == 6) {
self.year = arr[0];
self.month = arr[1];
self.day = arr[2];
self.hour = arr[3];
self.minute = arr[4];
self.second = arr[5];
}
self.timeStr = timeStr;
}
return self;
}
@end
- 獲取年月日還可以通過(guò)一下兩個(gè)方法
//1.NSDateFormat獲取
NSDate *date =[NSDate date];
NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
[formatter setDateFormat:@"yyyy"];
NSInteger currentYear=[[formatter stringFromDate:date] integerValue];
[formatter setDateFormat:@"MM"];
NSInteger currentMonth=[[formatter stringFromDate:date]integerValue];
[formatter setDateFormat:@"dd"];
NSInteger currentDay=[[formatter stringFromDate:date] integerValue];
NSLog(@"currentDate = %@ ,year = %ld ,month=%ld, day=%ld",date,currentYear,currentMonth,currentDay);
//2.NSDateComponents獲取
NSDate *currentDate = [NSDate date];
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *components = [calendar components:NSCalendarUnitYear|NSCalendarUnitMonth|NSCalendarUnitDay fromDate:currentDate];
NSInteger year=[components year];
NSInteger month=[components month];
NSInteger day=[components day];
NSLog(@"currentDate = %@ ,year = %ld ,month=%ld, day=%ld",currentDate,year,month,day);
最后編輯于 :
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者