Search code examples
androiddatedatetimejava-timeandroid-date

Parse date milliseconds to days,hours,minutes


I'm trying to get parse a string to date, and after that to get the days, hours & minutes from the milliseconds. I'm parsing this string to date:2015-03-01 00:00:00, and that I'm doing with this code:

DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date inputDate = dateFormat.parse(data.get(position).getValidTo());
long ms = inputDate.getTime();

Now after this I'm trying to get days, hours & minutes by doing this:

mins=(ms/(1000*60))%60;
hours=(ms/(1000*60*60))%24;
days=(ms/(1000*60*60*24));

and when I display it I get this:

16494Days : 22 hours : 58 minutes, as you can see the days are too far away today is 16th feb, and the expiring date is 1st of March.

What is wrong here?


Solution

  • Actually you need to get difference between current date and input date. after that you can perform these calculations like this

    DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    Date inputDate = dateFormat.parse(data.get(position).getValidTo());
    long ms = inputDate.getTime();
    
    long currentMilliSeconds=System.currentTimeMillis();
    
    ms = ms - currentMilliSeconds;
    
    mins=(ms/(1000*60))%60;
    hours=(ms/(1000*60*60))%24;
    days=(ms/(1000*60*60*24));