如何把服务器下发的时间字符串转换为想要的格式

定义公用变量:

NSDateFormatter* DateFormater;
NSCalendar *calendar;
NSInteger flags;
NSDateComponents *comps;

初始化这些代码:

DateFormater = [[NSDateFormatter alloc] init];
[DateFormater setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
flags = NSCalendarUnitYear |NSCalendarUnitMonth |NSCalendarUnitDay |NSCalendarUnitWeekday |NSCalendarUnitHour |NSCalendarUnitMinute |NSCalendarUnitSecond;
comps = [[NSDateComponents alloc] init];

获得mm-DD时间:

NSString* str = @"2018-04-20 13:30:00";
NSDate *date =[DateFormater dateFromString:str];
comps = [calendar components:flags fromDate:date];
printf("date is: %02ld-%02ld\n",[comps month],[comps day]);

获得MM:HH时间段

NSString* str = @"2018-04-20 13:30:00";
NSDate *date =[DateFormater dateFromString:str];
comps = [calendar components:flags fromDate:date];
printf("date is: %02ld-%02ld\n",[comps month],[comps day]);
NSInteger h1 = [comps hour];
NSInteger m1 = [comps minute];
    
str = @"2018-04-20 14:30:00";
date =[DateFormater dateFromString:str];
comps = [calendar components:flags fromDate:date];
NSInteger h2 = [comps hour];
NSInteger m2 = [comps minute];
printf("time during is: %02ld:%02ld - %02ld:%02ld\n",h1,m1,h2,m2);

结果


6731523940712_.pic.jpg

你可能感兴趣的:(如何把服务器下发的时间字符串转换为想要的格式)