Jump to content
  • Advertisement
Sign in to follow this  
Kungfu Joe

Java - Keeping track of time

This topic is 3966 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Check this out, pretty basic:
public static void main(String[] args)
	{		
		
		int s = getSec();
		for(int i = 0; i == 0;)
		{
			int currS = getSec();
			if(currS > s)
			{
				System.out.println(s);
				
			}
			s = getSec();
		}
		
	}
	
	public static int getSec()
	{
		Calendar c = Calendar.getInstance();
		
		return c.get(Calendar.SECOND);
	}
Now, if one of you actually takes the time to import util, and set it in a class, compile and run, you'll see my issue. I'll tell you what it is anyway. It's supposed to count seconds (aka 1 2 3 4 5) etc on the current second. For some reason it skips seconds though. it'll go 1 2 3 5 6 8 10 etc. It'll do it appropriately (it'll wait 2 seconds to go from 3 to 5), but it still isn't right. If you are curious about what i'm doing, I'm slowing down the fps of a permanant loop by checking time, and only iterating when a new second rolls around (1 fps). So whats going on, and do you have any tips? Thanks KFJ

Share this post


Link to post
Share on other sites
Advertisement
Ugh....

Use System.currentTimeMillis() or System.nanoTime(). nanoTime is available since Java 1.5.

Calendar is very bad choice for precise timing.

Also, to detect only change in value:


int getSec() {
return System.currentTimeMillis() / 1000;
}

....

int oldTime = getSec();
while (true)
{
int newTime = getSec();
if (newTime > oldTime) {
System.out.println(s);
oldTime = newTime;
}

System.sleep(1); // let CPU breathe
}



You could also fix your code by changing second assignment to "s = currS;", instead of getSec().

Share this post


Link to post
Share on other sites
You shouldn't use the Calendar class for something like that. Here's a what I would do:


public class SecondTic {
public static void main(String[] args) {
long time = System.currentTimeMillis();
int tick = 1;
while(true) {
long now = System.currentTimeMillis();
if(time + 1000 < now) {
time = time + 1000;
System.out.println(""+tick);
tick++;
}
}
}
}

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

GameDev.net is your game development community. Create an account for your GameDev Portfolio and participate in the largest developer community in the games industry.

Sign me up!