0

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?

Cœur
  • 37,241
  • 25
  • 195
  • 267
Darko Petkovski
  • 3,892
  • 13
  • 53
  • 117
  • 1
    You haven't shown how you're getting `ms` at all - and we don't know what time zone you're in. (A short but complete program demonstrating the problem would help.) – Jon Skeet Feb 16 '15 at 11:41
  • @JonSkeet `long ms = inputDate.getTime();`, I've updated the code sorry – Darko Petkovski Feb 16 '15 at 11:43
  • 1
    You need to get difference between that two dates and then perform your days operation.. – kalyan pvs Feb 16 '15 at 11:43
  • 1
    Do you understand that `getTime()` returns the number of milliseconds since the Unix epoch? (Jan 1st 1970) – Jon Skeet Feb 16 '15 at 11:43
  • Date.getTime() - Returns the number of milliseconds since January 1, 1970, 00:00:00 GMT represented by this Date object. – Mohamed Feb 16 '15 at 11:44
  • @DarkoPetkovski the time in ms you want is diff between input date to current date.is that what you want and then you want to calculate the time in days hours and minutes format – amit bhardwaj Feb 16 '15 at 12:00

3 Answers3

1

Take a calendar to get these informations:

    Calendar c = Calendar.getInstance();
    c.setTime(inputDate );
    days =c.get(Calendar.DAY_OF_MONTH);
    hours= c.get(Calendar.HOUR_OF_DAY);
    mins = c.get(Calendar.MINUTE);
Jens
  • 67,715
  • 15
  • 98
  • 113
0

Try this to get the day of week

Calendar c = Calendar.getInstance();
c.setTime(yourDate);
int dayOfWeek = c.get(Calendar.DAY_OF_WEEK);
Mohamed
  • 2,342
  • 4
  • 21
  • 32
0

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));
Ali
  • 1,857
  • 24
  • 25