currentTimeMillis 和 % 的一点思考

System.currentTimeMillis 可以给出从 1970.1.1 0点到现在的毫秒数(格林威治时间),返回值类型是 long。问题是需要根据这个毫秒数来计算一下现在的时间(小时,分钟,秒数)
本来这个问题不难,但是我忘记了直接可以取余,我使用了一个类似于贪心的思想,写了三个 while 循环来计算。

既然有两种方法就顺便总结一下这两种方法,对于取余来说很适合不必关心做了多少重复工作,只关注最后一次的情况。
而使用循环可以知道做了多少次重复工作。

public class lianxi2 {
    public static void main(String[] args) {
        long timeMillis = System.currentTimeMillis(); 
        long totleSeconds = timeMillis/1000;
        long second = totleSeconds%60;
        long totleMinutes = totleSeconds/60;
        long minute = totleMinutes%60;
        long totleHour = totleMinutes/60;
        long hour = totleHour%24;
        System.out.println((hour+8)+":"+minute);
    }
}

你可能感兴趣的:(currentTimeMillis 和 % 的一点思考)