Java countdown (days/hours/mins)

Soldato
Joined
18 Oct 2002
Posts
9,047
Location
London
Having real trouble with this, maybe I just can't get my head around the numbers or maybe I'm going about it wrong? It's not homework or anything, just personal interest - turning into personal annoyance! :D


Code:
import java.text.*;
import java.util.*;

public class Test2  {

	public Test2() {}

	public static void main(String[] args) throws ParseException {
		Calendar cal = new GregorianCalendar();
		cal.set(Calendar.YEAR, Calendar.YEAR);
		cal.set(Calendar.MONTH, Calendar.NOVEMBER);
		cal.set(Calendar.DAY_OF_MONTH, 19);
		cal.set(Calendar.HOUR_OF_DAY, 12);
		cal.set(Calendar.MINUTE, 0);
		cal.set(Calendar.SECOND, 0);

		long then = cal.getTimeInMillis();

		long now = System.currentTimeMillis();


		int secs = (int) ((then - now) / 1000L);

		//int i = (int) seconds;
		//int time = i / 60;
		//int mins = time % 60;
		//int secs = i % 60;

		//int sec = (secs/60) % 60;
		int mins = (secs/(1000*60)) % 60;
		int hours = (secs/(1000*60*60)) % 24;
		int days = (secs/(1000*60*60*24)) % 7;

		String out = days + " days " + hours + " hours " + mins + " minutes " + secs + " seconds.";
		
		System.out.println(out);
	}
}


As you can see I've tried a few ways of doing things, but I just end up with output that makes no real sense. If someone could help that would be sooooo good :)
 
*1000? Yeah I've been using so many different things I've got myself confused!

This shouldn't be hard should it?

I've worked out the time in millseconds from now until the date I'm looking for (then - now).

So to go from ms to seconds I just / 1000 right?
Then to get minutes I just secs / 60
hours = mins / 60
days hours / 24

That sounds straight forward doesn't it? :/
 
int totalSeconds = currentTimeInMillis / 1000;
int seconds = totalSeconds % 60; // Anything over 60 will be removed
int minutes = (totalSeconds / 60) % 60; // Conversion to minutes by /60, then anything over 60 (ie an hour) will be removed
int hours = (totalSeconds / 60 / 60) % 24; //Conversion into hours by /60 /60 then anything over 24 hours will be removed;
int days = (totalSeconds / 60 / 60 / 24) // Days
 
Ahh that's sorted it, thanks :)

Although even with the 'correct' calculations I was ruining it by converting from long to int. So I've just left everything as long and it's perfect.

Also using :
cal.set(Calendar.YEAR, Calendar.YEAR);
Does not mean 2008 :o Had to set that to 2008, gahh...

Thanks :)
 
Back
Top Bottom