I am trying to create an app that calculates the time difference and the amount is multiplied by an amount in money. It is targeted to calculate in R$ (brazilian real) the amount that someone will have to pay for using a service during the time calculated by the app.
Here´s is my code:
- (IBAction)encerrar:(id)sender {
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
dateFormatter.dateFormat = @"HH:mm";
NSString *temp = inicio.text;
NSDate *then = [dateFormatter dateFromString:temp];
NSDate *now = [NSDate date];
NSTimeInterval timeInterval = [now timeIntervalSinceDate:then];
NSString *ext = [dateFormatter stringFromDate:now];
fim.text = ext;
NSDate *timerDate = [NSDate dateWithTimeIntervalSince1970:timeInterval];
[dateFormatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0.0]];
NSString *timeString = [dateFormatter stringFromDate:timerDate];
duracao.text = timeString;
double timeIntervalInHours = (timeInterval / 3600.0) * 5;
NSString *vTotal = [[NSString alloc] initWithFormat:@"R$ %.2f", fecha];
NSLog(@"%.2f", timeIntervalInHours);
vlrTotal.text = vTotal;
}
The fact is that when we click on Calculate button, and if the duracao (duration) is equal to 1h it gives me the correct amount which is R$ 5,00. But when the duration is equal to 30mins or other value different from exact 1h, it gives the wrong amount.
I.E.: 1h should be R$ 5,00; while 1:30h should be R$ 7,50, but shows me R$ 6,50.
So, anyone could help me on this???
Thanks in advance!!!
timeIntervalis the amount of time in seconds, so if you want it in hours and fractions of an hour just do this:and then multiple
timeIntervalInHourstimes the price/hour to get the cost.EDIT
Based on our chat, I would create a button with “iniciar” (start) as the title. When they press that button, I would store the current time and change the title to “encerrar” (stop). (I hope that my translations are correct, lol) Then the button action would look something like this:
startTime is declared as follows:
In your .h file, along with the other declared properties, add:
In your .m file, add this at the top with the other ones:
In your
viewDidUnloadfunction (in your .m file) add this:This just gives you a place to store the startTime date.