ios - Comparing Two NSDates with specific constraints -
i working accomplish within 3 statements, check compares 2 times (stored nsdates) , executes code based on difference between 2 respectively. checks wishing implement ( < 3min ), ( > 3min < 3hrs ), , ( > 3hrs ). below recent attempt. suggestions appreciated, thank you!
nsdateformatter* df = [[nsdateformatter alloc] init]; [df setlocale:[[nslocale alloc] initwithlocaleidentifier:@"en_us"]]; [df settimezone:[nstimezone systemtimezone]]; [df setdateformat:@""]; [df setdateformat:@"hh:mm mm-dd-yyyy"]; nsdate* newdate = [df datefromstring:[df stringfromdate:[[_radios objectatindex:indexpath.row] attributeforkey:@"date_time_edt"]]]; nstimeinterval interval = [newdate timeintervalsincenow]; if(interval < 3 * 60) { img.image = [uiimage imagenamed:@"tire_green.png"]; nslog(@"%@", newdate); nslog(@"%f", interval); } else if(interval > 3 * 60 && interval < 3 * 60 * 60) { img.image = [uiimage imagenamed:@"tire_yellow.png"]; nslog(@"%@", newdate); } else { img.image = [uiimage imagenamed:@"tire_red.png"]; nslog(@"%@", newdate); }
updated based on far long comment thread.
it turns out [[_radios objectatindex:indexpath.row] attributeforkey:@"date_time_edt"]
returning nsnumber
representing number of milliseconds since january 1st, 1970. there no need date formatters. can date value follows (which needs seconds, not milliseconds):
nsnumber *timestamp = [[_radios objectatindex:indexpath.row] attributeforkey:@"date_time_edt"]; nsdate *newdate = [nsdate datewithtimeintervalsince1970:[timestamp doublevalue] / 1000];
now can time interval since "now". keep in mind resulting interval negative if newdate
in past (which true in case).
nstimeinterval interval = [newdate timeintervalsincenow];
since know interval
negative since newdate
in past, checks easier if make positive.
interval = -interval; // positive
now can needed checks desired image.
if (interval < 3 * 60) { // < 3 minutes img.image = [uiimage imagenamed:@"tire_green.png"]; } else if (interval > 3 * 60 * 60) { // > 3 hours img.image = [uiimage imagenamed:@"tire_red.png"]; } else { // >= 3 minutes && <= 3 hours img.image = [uiimage imagenamed:@"tire_yellow.png"]; }
Comments
Post a Comment