3

I'm making a game with a timer and it tell's you how long you took to complete the game at the end, it's a basic game so some people may beat it in less than a minute so i want to know is there any way to detect if there if the minutes are equal to 00 so then i can set the text to say 00:12 seconds and if it's not equal to 00 then it will say 01:12 Minutes. This is the code that i am using to work out the times.

Date start = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("mm:ss");

And the work out the final time is simply

Date now = new Date();
sdf.format(new Date(now.getTime() - start.getTime()))
mKorbel
  • 109,525
  • 20
  • 134
  • 319
Bill Nye
  • 831
  • 1
  • 10
  • 15

2 Answers2

3

Fixed it.

Date start = new Date();
SimpleDateFormat sdfm = new SimpleDateFormat("mm");
SimpleDateFormat sdfs = new SimpleDateFormat("ss");

Date now = new Date();

if(sdfm.format(new Date(now.getTime() - start.getTime())).equals("00")){
JOptionPane.showMessageDialog(null, "You Won!! It only took you " + sdfs.format(new Date(now.getTime() - start.getTime())) + " Seconds", "You Won!!", 1);
    }else{  
JOptionPane.showMessageDialog(null, "You Won!! It only took you " + sdfm.format(new Date(now.getTime() - start.getTime())) +  ":" + sdfs.format(new Date(now.getTime() - start.getTime())) + " Minutes", "You Won!!", 1);
System.exit(0);
Bill Nye
  • 831
  • 1
  • 10
  • 15
2
long start = System.currentTimeMillis();

/*
 * Your code
 */

long diff = System.currentTimeMillis() - start;

long seconds = (diff / 1000) % 60;
long minutes = (diff / (1000 * 60)) % 60;
long hours = (diff / (1000 * 60 * 60)) % 24;

System.out.println("Total " + hours + " hours " + minutes + " minutes " + seconds + " seconds");

Refer below links for another possible solutions,

Java-How to calculate accurate time difference while using Joda Time Jar

How can I calculate a time span in Java and format the output?

Darshan Patel
  • 2,839
  • 2
  • 25
  • 38