我正在研究IRC Twitch.tv BOT(PircBot),我想实现一个!uptime chatcommand,它将显示Stream在线的时间。
我在谷歌搜索了一下,我只找到了需要GUI的解决方案。
Some1可以告诉我哪些库好用或给我一些示例代码?
我需要显示秒,分,小时,天。
首先,我考虑做一个普通的计时器,它计算+1秒,但我认为它更容易,并且有一些适当的功能来处理这样的“计数” - 对吧?对不起?
我有任何提示!
谢谢:)
这就是我现在想出的:
在我的Main课程中,我有一个我打电话的计时器:
utimecounttimer();
我的计时器如下所示:
public void utimecounttimer() {
uptimetimer.scheduleAtFixedRate(new TimerTask() {
@Override
public void run() {
if (isstreamlive == true){
UptimeCount.Uptimestart();
}else{
UptimeCount.Uptimestop();
}
}
}, 1000, 1000);
}
然后我的UptimeCount类就在这里:
public class UptimeCount {
public static long startTime = 0;
public static long OnlineTimeMillis = 0;
public static float OnlineTimeSec = 0;
public static float OnlineTimeMin = 0;
public static float OnlineTimeHour = 0;
public static float OnlineTimeDay = 0;
public static void Uptimestart(){
if(startTime == 0){
startTime = System.currentTimeMillis();
}else
if(startTime != 0){
OnlineTimeMillis = System.currentTimeMillis()-startTime;
OnlineTimeSec = OnlineTimeMillis /1000F;
OnlineTimeMin = OnlineTimeMillis /(60*1000F);
OnlineTimeHour = OnlineTimeMillis /(60*60*1000F);
OnlineTimeDay = OnlineTimeMillis /(24*60*60*1000F);
}
System.out.println("Seconds"+OnlineTimeSec);
System.out.println("Minutes"+OnlineTimeMin);
System.out.println("Hours"+OnlineTimeHour);
System.out.println("Days"+OnlineTimeDay);
}
public static void Uptimestop(){
startTime = 0;
OnlineTimeMillis = 0;
OnlineTimeSec = 0;
OnlineTimeMin = 0;
OnlineTimeHour = 0;
OnlineTimeDay = 0;
}
}
然后,最后但并非最不重要的是,我在主要课程中与以下一行聊天时获取信息:
if (message.equalsIgnoreCase("!uptime")) {
sendMessage(channel," Stream is running for: "+UptimeCount.OnlineTimeDay +" Days, "+UptimeCount.OnlineTimeHour +" Hours. "+UptimeCount.OnlineTimeMin +" Minutes and " +UptimeCount.OnlineTimeSec +" Seconds.");
}
我还没有测试它但我认为我必须格式化浮点数的ms输出然后它应该正常工作,对吗?
答案 0 :(得分:1)
// it will give you current time in mille seconds
long startTime = System.currentTimeMillis();
// Mill second diffrence
long OnlineTimeMillis = System.currentTimeMillis()-startTime;
// time diff in mille seconds since you are online
float OnlineTimeSec = OnlineTimeMillis /1000F;
// time diff in Minutes since you are online
float OnlineTimeMin = OnlineTimeMillis /(60*1000F);
// time diff in Hours since you are online
float OnlineTimeHour = OnlineTimeMillis /(60*60*1000F);
// time diff in days since you are online
float OnlineTimeDay = OnlineTimeMillis /(24*60*60*1000F);
答案 1 :(得分:1)
您可以使用Joda Time来表示持续时间和时间:
// at startup of the stream
DateTime startedAt = DateTime.now();
// later
Duration elapsed = new Duration(startedAt, DateTime.now());
并且可以使用描述in this answer的解决方案来格式化输出,以获得人类可读的输出(即“1小时2分钟”)。
请同时检查Duration,因为它有toStandardHours
,toStandardMinutes
等方法,可用于显示小时/分钟等总数。已过去(即“1小时| 62分钟”)。