0

I am working on application on which one time saved on firebase and other is current user time. When app start it retrieve firebase time with date and get current user date and find its minutes. But issue is that it calculate exact when date is same mean first date time is 28/03/2020 10:00 and second one is 28/03/2020 11:00. But when date time is like first 27/03/2020 10:00 and second one is 28/03/2020 01:00 then it does not calculate according to date it also again calculate it according to same day and shows 3 hours. If dates too much vary it shows the result in negative sign. I am searching too much but can not found its best solution also on stack-overflow. Most of accepted answers do the same code like me for this problem but nothing work for me.

My code is:

SimpleDateFormat format = new SimpleDateFormat("DD/MM/YYYY HH:mm");

String currentTime = format.format(Calendar.getInstance().getTime());

try {
    d1 = format.parse(currentTime);
    d2 = format.parse(submitTime);
} catch (ParseException e) {
    e.printStackTrace();
}

long duration  = d1.getTime() - d2.getTime();
Toast.makeText(this, ""+duration, Toast.LENGTH_LONG).show();
int minutes= (int) TimeUnit.MILLISECONDS.toMinutes(duration);

if (minutes>=60)
{
    int hrs = (int) TimeUnit.MINUTES.toHours(minutes);
    mOut.setText(""+hrs+"h "+minutes+"min");
}
else if (minutes>1440)
{
    int days = (int) TimeUnit.MINUTES.toDays(minutes);
    mOut.setText(""+days+"days");
}
else
{
    mOut.setText(""+minutes);
}

getFinal = Integer.parseInt(timeS)-minutes;
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • 2
    As an aside consider throwing away the long outmoded and notoriously troublesome `SimpleDateFormat` and friends, and adding [ThreeTenABP](https://github.com/JakeWharton/ThreeTenABP) to your Android project in order to use java.time, the modern Java date and time API. It is so much nicer to work with. – Ole V.V. Mar 28 '20 at 12:33

1 Answers1

2

The problem is mostly your SimpleDateFormat.

You use capital 'D', wich denotes "Day of Year", you probably want lower case 'd' which denotes "Day of Month"

You use capital 'Y', which denotes "Week year", you probably want lower case 'y' which denotes "Year"

bowmore
  • 10,842
  • 1
  • 35
  • 43