日期:2014-05-20  浏览次数:20753 次

J2ME时间差求法?
游戏开始时间获取?
游戏结束时间获取?
后他们时间差,多少秒?多少分?

麻烦给个程序,谢谢!

------解决方案--------------------
时间处理在程序开发中相当常见,下面对于时间处理做一个简单的说明。
一、时间的表达方式
时间在J2ME中有两种表达方式:
1、 以和GMT1970年1月1号午夜12点和现在相差的毫秒数来代表
这种方式适合比较两个时间之间的差值。
2、 以对象的形式来表达
二、时间处理的相关类
时间处理在J2ME中涉及三个类:
1、 System类
long time = System. currentTimeMillis();
使用该方法可以获得当前时间,时间的表达方式为上面提到的第一种。
2、 Date类
Date date = new Date();
获得当前时间,使用对象的形式来进行表达。
3、 Calendar类
Calendar calendar = Calendar. getInstance();
三、时间处理的具体操作
1、 以上三种表达方式的转换:
a) 将System类获得的时间转换为Date对象
Date date = new Date(System. currentTimeMillis());
b) 将Date类型的对象转换为Calendar类型的对象
Calendar calendar = Calendar. getInstance();
Date date = new Date();
calendar.setTime(date);
2、 使用Calendar完成一些日期操作:
Calendar是时间处理中最常用也是功能最强大的类,可以用它来获得某个时间的日期、星期几等信息。
获得日期:
Calendar calendar = Calendar. getInstance();
……
int day = calendar.get(Calendar. DATE);
获得日期、年份、星期的操作和这个类似。

需要注意的是:Calendar中表示月份的数字和实际相差1,即1月用数字0表示,2月用数字1表示,……12月用数字11表示。


在游戏开发中,有时候我们需要一个时钟来记录游戏的时间,如果时间结束则结束游戏。本文介绍如何在J2ME中使用Timer和TimerTask来实现这样一个时钟,并给出具体代码实例。
  在java.util包中有一个TimerTask类,你可以扩展这个类并且实现他的run()方法,在run()方法中编写我们的逻辑代码。如果我们想制作一个游戏时钟,那么非常简单我们编写一个GameClock类扩展TimerTask,GameClock需要维持一个实例变量timeLeft,这样我们就可以记录游戏剩余的时间了,在每次run()运行的时候把timeLeft减1就可以了。有时候我们需要始终暂停以及重新启动,这并不复杂,在GameClock中添加一个boolean类型的标记就可以了。下面给出GameClock的代码:

/*
* GameClock.java
*
* Created on 2005年7月18日, 上午11:00
*
* To change this template, choose Tools | Options and locate the template under
* the Source Creation and Management node. Right-click the template and choose
* Open. You can then make changes to the template in the Source Editor.
*/

package com.j2medev.gameclock;
import java.util.TimerTask;
/**
*
* @author Administrator
*/
public class GameClock extends TimerTask{

private int timeLeft = 60;//时钟的默认时间
private boolean pause = false;
/** Creates a new instance of GameClock */
public GameClock() {
}

public GameClock(int value){
timeLeft = value;
}

public void run(){
if(!pause){
timeLeft--;
}
}

public void pause(){
pause = true;
}

public void resume(){
pause = false;
}

public int getTimeLeft(){
return timeLeft;
}

public void setTimeLeft(int _value){
this.timeLeft = _value;
}
}

  当我们使用这个时钟的时候,只需要把它的一个实例作为参数传给Timer的schedule()方法即可。例如

clock = new GameClock(30);
timer.schedule(clock,0,1000);

  接下来我们编写一个简单的游戏界面测试一下时钟。我们在程序启动的时候开始计时,每隔一秒钟timeLeft会减少1,并且在手机屏幕上显示当前剩余的时间。如果timeLeft为0的时候代表游戏已经结束了。因此我们需要这样判断游戏的状态。

public void verifyGameState(){
timeLeft = clock.getTimeLeft();
if(timeLeft == 0){
going = false;
}
}

  为了测试时钟的暂停功能,我们接收用户的按键行为,如果左键被按下,那么调用clock的pause()方法,如果右键被按下则调用clock的resume()方法。

public void userInput(){
int keyStates = this.getKeyStates();
if((keyStates & GameCanvas.LEFT_PRESSED) != 0){
clock.pause();
}else if((keyStates & GameCanvas.RIGHT_PRESSED) != 0){
clock.resume();
}

}

  下面给出MIDlet和Canvas的代码:

/*
* ClockCanvas.java
*
* Created on 2005年7月18日, 上午11:04