繁体   English   中英

如何从用户定义的时间中减去系统时间

[英]how to subtract system time from user defined time

任何人都可以建议我找到系统时间与用户定义的时间之间的间隔,例如我的小时= 20和分钟= 12。

要获得两个日期/日历对象之间的差异,最好以毫秒(长)为单位。

    Calendar current = Calendar.getInstance();
    Calendar usertime = Calendar.getInstance();
    usertime.set(Calendar.HOUR_OF_DAY, 20);
    usertime.set(Calendar.MINUTE, 12);

    long diffInMilisecond = Math.abs(usertime.getTimeInMillis()-current.getTimeInMillis());

如果您可以使用第三方api,那么在上述情况下, Joda时间将非常有用。 这里

为什么要麻烦用户输入所需的时间而不是从当前时间输入多长时间? 当映射到倒数计时器的概念时,它更有意义。

如果您要为用户指定的时间设置计时器,这就是我的方法。

//Get user input into variable hours, and minutes
Timer timer = new Timer();
timer.schedule(new TimerTask() {
    public void run() {
        //do stuff when countdown has happened
    }, (((hours * 60) + minutes) * 60) * 1000)); //time in milliseconds to exec run
}

编辑

如果您只想计算用户输入小时和分钟时的时间差,请尝试以下操作:

//Get user input into variable hours, and minutes
Calendar cal = new GregorianCalendar();
//Assuming user inputs hour in 24 hour format and inputted time is in future
totalMinsDiff = (hours - cal.get(Calendar.HOUR_OF_DAY)) * 60 + 
      minutes - cal.get(Calendar.MINUTE); 
countdownHours = totalMinsDiff / 60;
countdownMins = totalMinsDiff % 60;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM