如何确定SimpleDateFormat是使用秒还是分钟

时间:2015-12-06 04:41:52

标签: java swing simpledateformat

我用计时器制作游戏,它告诉你最后完成游戏需要多长时间,这是一个基本的游戏,所以有些人可能会以低于一分钟,所以我想知道有没有办法检测是否有分钟等于00所以然后我可以设置文字说00:12秒,如果它不等于00那么它会说01:12分钟这是我用来计算时代的代码。

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

最后一次的工作就是

Date now = new Date();
sdf.format(new Date(now.getTime() - start.getTime()))

2 个答案:

答案 0 :(得分:3)

修正了它。

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);

答案 1 :(得分: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");

请参阅以下链接,了解其他可能的解决方案,

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?