I want to charge my users 1 credit for each hour or fraction they use a service.
To calculate the cost I'm using the following code, but in some cases, for example when the starting and ending dates are exactly at one day difference, I get a cost of 25 credits instead of 24:
NSNumberFormatter *format = [[NSNumberFormatter alloc]init];
[format setNumberStyle:NSNumberFormatterDecimalStyle];
[format setRoundingMode:NSNumberFormatterRoundUp];
[format setMaximumFractionDigits:0];
[format setMinimumFractionDigits:0];
NSTimeInterval ti = [endDate timeIntervalSinceDate:startDate];
float costValue = ti/3600;
self.cost = [format stringFromNumber:[NSNumber numberWithFloat:costValue]];
What am I doing wrong?
NSTimeInterval has sub-millisecond precision. If the dates are one day and a millisecond apart, you would charge the 25-th credit.
Changing the code to do integer division should deal with the problem:
// You do not need sub-second resolution here, because you divide by
// the number of seconds in the hour anyway
NSInteger ti = [endDate timeIntervalSinceDate:startDate];
NSInteger costValue = (ti+3599)/3600;
// At this point, the cost is ready. You do not need a special formatter for it.
Related
I am reading system time(Register: TM11), and I want to get minute data from system time.
system time is in this data format = 3 bytes:{Hour}{Minute}{Second}
I am not sure, how to extract "minute" data, using array format, C code as below.
In my C code below, i use read_register function for reading system time, and use pointer (byte*)&systime[1]) to extract "minute". -not sure this is correct way to do so.
let's say, time now is 07:48:29 AM then, TM11 will show 07,48,29
I want to extract "48", which is minute, from TM11.
time interval: 15 minute.
Time Passed = 48 % 15 = 3 minute.
Putting this calculation in the C,
byte systime[2];
//declare "systime" variable as 3 byte array and to store TM11 //
byte time_interval = 15; //time interval is 15 minute
read_register (TM11,(byte*)&systime[1]);
//let's say read data value of TM11 is, 07:48:29 AM
//"read_register"function is to read the value of TM11 register
//(byte*)&systime[1] =try to point "minute" in TM11 register, systime[1]=48
//I am not sure whether hour will store in systime[0], minute will store in systime[1],//
elaps_time = systime[1] % time_interval;
//elapsed time calculation = 48 % 15 = 3
I'm currently working on a small project on handling time difference on MATLAB. I have two input files; Time_in and Time_out. The two files contain arrays of time in the format e.g 2315 (GMT - Hours and Minute)
I've read both Time_in' and 'Time_out on MATLAB but I don't know how to perform the subtraction. Also, I want the corresponding answers to be in minutes domain only e.g (2hrs 30mins = 150minutes)
this is one of several possible solutions:
First, you should convert your time strings to a MATLAB serial date number. If you've done this, you can do your calculation as you want:
% input time as string
time_in = '2115';
time_out = '2345';
% read the input time as datenum
dTime_in = datenum(time_in,'HHMM');
dTime_out = datenum(time_out,'HHMM');
% subtract to get the time difference
timeDiff = abs(dTime_out - dTime_in);
% Get the minutes of the time difference
timeout = timeDiff * 24 * 60;
Furthermore, to calculate the time differences correctly you also should put some information about the date in your time vector, in order to calculate the correct time around midnight.
If you need further information about the function datenum you should read the following part of the MATLAB documentation:
https://de.mathworks.com/help/matlab/ref/datenum.html
Any questions?
In a recent version of MATLAB, you could use textscan together with datetime and duration data types to do this.
% read the first file
fh1 = fopen('Time_in');
d1 = textscan(fh1, '%{HHmm}D');
fclose(fh1);
fh2 = fopen('Time_out');
d2 = textscan(fh2, '%{HHmm}D');
fclose(fh2);
Note the format specifier '%{HHmm}D' tells MATLAB to read the 4-digit string into a datetime array.
d1 and d2 are now cell arrays where the only element is a datetime vector. You can subtract these, and then use the minutes function to find the number of minutes.
result = minutes(d2{1} - d1{1})
I am in WinCE7 and to get the current time, I am using GetLocalTime(&systemTime);. This function gives the value of current time. Now if the milliseconds is 81, it displays it as 81 due to which the error occurs when I subtract two time values. For ex: time1 : 12:34:13:851 & time2: 12:34:14:81. Now I need to subtract seconds and milliseconds. So using sprintf, I am extracting seconds and milliseconds and putting them in time1 & time2 :
sprintf(time1,"%d.%d",systemTime.wSeconds,systemTime.wMilliseconds)
sprintf(time2,"%d.%d",systemTime.wSeconds,systemTime.wMilliseconds)
I am converting time1 & time2 into float using atof.Now time1 is 13.851 and time2 is 14.81. The milliseconds of time2 is actually 081 but it displays 81 so while subtracting it consider it as 810 which gives wrong values.
time2--> 14.810 14.081
time1--> 13.851 13.851
-------- ---------
result 0.959(wrong) 0.23(correct)
So to remove this error I thought of counting the digits of milliseconds and if it is 2 then add 0 at starting. So I did:
double digits = (floor (log10 (abs (milliseconds))) + 1); //calculate digits
if(digits == 2) //if milliseconds contains 2 digits, we need to add 0 at starting
{
sprintf(newMS,"0%d",milliseconds); //adding 0 to milliseconds
finalMilliseconds = atoi(newMS); //newMS is in char so converting it into integer and storing the value in finalMilliseconds
}
The problem occurs here. Lets say milliseconds = 18, so newMS = 018 but finalMilliseconds is again 18.
Please suggest any other way of conversion or any other way of adding 0 at starting
According to the documentation of SYSTEMTIME from MSDN:
It is not recommended that you add and subtract values from the
SYSTEMTIME structure to obtain relative times. Instead, you should
Convert the SYSTEMTIME structure to a FILETIME structure.
Copy the resulting FILETIME structure to a ULARGE_INTEGER structure.
Use normal 64-bit arithmetic on the ULARGE_INTEGER value.
The example here will give you some idea on how to get started.
It seems to me the simplest solution is to borrow what you need.
You already have integers. If you're subtracting two systemTime values, t2 from t1, say,
if( t1.wMilliseconds < t2.wMilliseconds ) {
t1.wMilliseconds += 1000;
t1.wSeconds--;
}
Or, just perform the subtraction. If the result's wMlliseconds is negative, adjust as above.
Take care to ensure t1 > t2, though. You don't want -1.25 = 0.0 - 0.75.
Instead of putzing with strings, if you want a float, make one:
double time1 = t1.wSeconds + 0.001 * t1.wMilliseconds;
C does the conversion for you. It's faster, more direct, and less error-prone than going through strings.
Another way of dealing with these marvels of lost leading or trailing zeroes (found in time and longlat), is to right pad the string with say four zeroes .i.e your newMS+"0000", and take the leftmost four characters.
You then have a number (as text) ranging from "0000" to "9990".
Put a "1" in front of it, then you can easily and unambiguously convert to an integer between 10000 and 19990.
Then you can add and subtract as you like.
Clumsy? Yes indeed :) But I have had to do weird tricks like this when GPS longitude readings go from 11.59(funny numbers) to 12.00
I have a longitudinal (person-level) dataset I am looking to for syntax for counting the number of times an event happened up to a certain point. More specifically I have 200 weeks of data (each week is coded 1-7, I'm only interested in weeks where the value is 5 or greater), But I am only interested in weeks that happened before a certain time point (the time point is different for each person but and captured under a single variable "eventweek"). So for person Y whose eventweek = 154, I want to know what percentage of weeks before week 154 (wks 1-153) where that person was coded a 5 or above. For person Z whose eventweek = 52, I want to know what percentage of weeks before week 52 (wks 1-51) for which that person was coded a 5 or above, and so on.
Any ideas on how to code this?
Try the following:
vector v = week1 to week200.
compute #z = 0.
loop #i = 1 to (eventweek -1).
compute #z = #z + (v(#i) ge 5).
end loop.
compute ew_perc = #z/(eventweek -1)*100.
exe.
I'm having a lot of trouble dealing with with a particular question in my critical thinking class.
The task is this:
Task
Develop an algorithm to prompt for and obtain maximum daily temperatures for a whole year. However, in order to consider leap years, your algorithm should first prompt the user for the number of days in this particular year. That is, your algorithm should expect 365 or 366 as the first input number followed by input temperature values.
In addition, for this particular year, your algorithm must also determine and display the average, maximum, and minimum of these temperatures values.
Here's an example of what needs to happen:
Prompt for number of days in a year
(let's say they enter 365)
Then prompt user for MAXIMUM daily tempretures for 365 days.
Take those 365 (individual) maximum tempretures, find the lowest value that will = Min_temp.
Take those 365 (individual) maximum tempretures, find the highest value that will = Max_temp.
Sum up all 365 invidual max tempretures and divide it by the number of days in the year (365) = Avg_temp.
Print Min_temp
Print Max_temp
Print Avg_temp
So far this is what I have:
1. Prompt operator to enter Number_Of_Days within year.
2. WHILE Number_Of_Days = 365 or 366 THEN
3. IF Number_Of_Days is = 365 THEN
4. Year = 365
5. ELSEIF Number_Of_Days = 366 THEN
6. Year = 366
7. ENDIF
8. ELSEWHILE Number_of_Days is NOT = 365 or 366 THEN
9. Print ‘ERROR: Please enter a number that is 365 or 366.’
10. Prompt operator to enter Number_Of_Days within year.
11. ENDWHILE
12. DOWHILE MaxDayTemp = 1 to Year
16. Prompt operator for MaxDailyTemp
15. ENDO
From here we're meant to get an average of all the maximum temps provided by the user, that's easily done by AVG_TEMP = Sum of Temps / Days in the year.
What I can't work out is how to take the values of each day and find the lowest and highest values that are provided.
I've been trying to work it out with an array but I'm totally confused by it.
Please help! :(
I think you are expecting something like this, tried to use your conversion. Format it as you want.
i=0;
tempsum=0;
tempmax=0;
tempmin=100;
currenttemp=0;
no_days=0;
// variables used to store values
do
(prompt user for number of days)
no_days = user input
while no_days!=365 or no_days!=366 // will loop until user enter 365 or 366
while i<no_days
do
(Prompt operator for MaxDailyTemp)
currenttemp = userinput
while (currenttemp value is invalid) // thinking in the same way as above
if currenttemp > tempmax
tempmax = currenttemp
else if currenttemp < tempmin
tempmin = currenttemp
tempsum = tempsum + currenttemp
i = i+1
end
display average temp. = tempsum/no_days
display max temp. = tempmax
display min temp. = tempmin
I don't know what syntax is required for your class but this
max = (1 st value)
min = (1 st value)
i = 2
WHILE i < year THEN
IF (i th value) > max THEN
max = (i th value)
ELSIF (i th value) < min THEN
min = (i th value)
i = i + 1
would get the min and max value.