In iOS development, it is often necessary to get time from background data, but the time format returned in the background is often a string of numbers similar to "123456789", which is the number of seconds since 1970, when we need to convert it to a format that we can use.
In the model I defined the C_time property by overriding the conversion in the format of the C_time get method.
-(NSString *) c_time{//1. Create Time Format classNSDateFormatter *formatter =[[NSDateFormatter alloc] init]; //2. Format the time//YYYY-MM-DD HH:mm:ss#warningNote: In the case of real-time development, in addition to formatting, you also need to set the format corresponding to the region, otherwise the format may be nullFormatter.locale= [[Nslocale alloc] Initwithlocaleidentifier:@"en_US"]; Formatter.dateformat=@"EEE MMM dd HH:mm:ss Z yyyy"; //3. Conversion TimeNSDate *cretedate =[Formatter datefromstring:_c_time]; //4. Processing Time if([cretedate isthisyear]) {//this year if([cretedate isToday]) {//TodayNsdatecomponents *cmps =[Cretedate Deltawithnow]; if(Cmps.hour >=1) {Formatter.dateformat= [NSString stringWithFormat:@"%ld hours ago", (Long) Cmps.hour]; return[Formatter stringfromdate:cretedate]; }Else if(Cmps.minute >=1) {Formatter.dateformat= [NSString stringWithFormat:@"%ld minutes ago", (Long) Cmps.minute]; return[Formatter stringfromdate:cretedate]; }Else { return @"just"; } }Else if([cretedate isyesterday]) {//YesterdayFormatter.dateformat =@"yesterday HH when mm points"; return[Formatter stringfromdate:cretedate]; }Else { //Other daysFormatter.dateformat =@"MM month dd Day hh mm min"; return[Formatter stringfromdate:cretedate]; } }Else { //not this yearFormatter.dateformat =@"yyyy mm month DD Day HH"; return[Formatter stringfromdate:cretedate]; } return_c_time;}
How to convert the time returned in the background to a common string in iOS development