- So before this I already get the time difference between two times.
- Now, I want to display point that will be charged for specific time duration like this: in my code, time duration named as diffResult, if diffResult less than 30 minutes, point will be charged is multiply by 1 diffResult =2, so 2*1 ,point will be charged is 2.
I wanted to use if else statement, but I got some errors. Here is my code
pointChargeBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { SimpleDateFormat simpleDateFormat = new SimpleDateFormat("HH:mm a"); Date date1 = null; try { date1 = simpleDateFormat.parse(timeResult.getText().toString()); } catch (ParseException e) { e.printStackTrace(); } Date date2 = null; try { date2 = simpleDateFormat.parse(timeResult2.getText().toString()); } catch (ParseException e) { e.printStackTrace(); } String diffResult= DateUtils.getRelativeTimeSpanString(date1.getTime(), date2.getTime(), DateUtils.MINUTE_IN_MILLIS).toString(); if(diffResult < 30){ int point = diffResult * 2; pointChargeBtn.setText(point); } } });
Asked
Active
Viewed 58 times
0

Nor Sakinah
- 49
- 8
-
post which errors you face? and which thing user can enter?time or date? which format? – Janvi Vyas May 01 '18 at 09:38
-
In your code diffResult is a String. Operator '<' cantnot be applied to a String. – will May 01 '18 at 09:54
-
since diffResult is a String so can't compare with integer in the if statement. Button to display time. The format is SimpleDateFormat and MINUTES_IN_MILLIS @Janvi Vyas – Nor Sakinah May 02 '18 at 06:54
-
do I have to convert the diffResult from string to and integer? @will – Nor Sakinah May 02 '18 at 06:56
-
@NorSakinah you can get hours from diffResult like so: diffResult.split(" ")[0] than cast it to an Integer like so: new Integer(diffResult.split(" ")[0]) . Now you have the hours as an int and can compare it like you are doing above – will May 02 '18 at 07:30
1 Answers
0
Your error is:
String diffResult= DateUtils.getRelativeTimeSpanString(date1.getTime(), date2.getTime(), DateUtils.MINUTE_IN_MILLIS).toString();
if(diffResult < 30){
int point = diffResult * 2;
pointChargeBtn.setText(point);
}
diffResult
is a String
so you can't compare it with a number neither multiply it
EDIT
You can fix it like that:
// difference in milliseconds
// Using Math.abs is optional. It allows us to not care about which date is the latest.
int diffInMillis = Math.abs(date2.getTime() - date1.getTime());
// Calculates the time in minutes
int diffInMinutes = diffInMillis / (1000 * 60);
// if difference is less (strictly) than 30 minutes
if (diffInMinutes < 30){
// TODO: Do something
}

Eselfar
- 3,759
- 3
- 23
- 43
-
-
But you're aware that your app will crash if there is any parsing error? You should test if both dates are not `null` and do something if this is the case (e.g. display an error message to the user), before trying to calculate the time difference – Eselfar May 02 '18 at 08:07