制作一个倒数计时器

 林林7089 发布于 2023-02-12 18:31

我想从android当前时间制作新年的倒数计时器...

Calendar thatDay = Calendar.getInstance();
thatDay.set(Calendar.DAY_OF_MONTH,1);
thatDay.set(Calendar.MONTH,0); // 0-11 so 1 less
thatDay.set(Calendar.YEAR, 2014);

Calendar today = Calendar.getInstance();
long diff =  thatDay.getTimeInMillis() - today.getTimeInMillis(); 

现在如何将此差异转换为日,小时,分钟,秒格式?请帮忙

1 个回答
  • 以下代码

    import java.util.Date;
    import java.util.Calendar;
    
    public class cal {
        public static int SECONDS_IN_A_DAY = 24 * 60 * 60;
        public static void main(String[] args) {
            Calendar thatDay = Calendar.getInstance();
            thatDay.setTime(new Date(0)); /* reset */
            thatDay.set(Calendar.DAY_OF_MONTH,1);
            thatDay.set(Calendar.MONTH,0); // 0-11 so 1 less
            thatDay.set(Calendar.YEAR, 2014);
    
            Calendar today = Calendar.getInstance();
            long diff =  thatDay.getTimeInMillis() - today.getTimeInMillis(); 
            long diffSec = diff / 1000;
    
            long days = diffSec / SECONDS_IN_A_DAY;
            long secondsDay = diffSec % SECONDS_IN_A_DAY;
            long seconds = secondsDay % 60;
            long minutes = (secondsDay / 60) % 60;
            long hours = (secondsDay / 3600); // % 24 not needed
    
            System.out.printf("%d days, %d hours, %d minutes and %d seconds\n", days, hours, minutes, seconds);
        }
    }
    

    产生

    27 days, 17 hours, 18 minutes and 2 seconds
    27 days, 17 hours, 18 minutes and 1 seconds
    27 days, 17 hours, 18 minutes and 0 seconds
    27 days, 17 hours, 17 minutes and 59 seconds
    27 days, 17 hours, 17 minutes and 58 seconds
    27 days, 17 hours, 17 minutes and 57 seconds
    27 days, 17 hours, 17 minutes and 56 seconds
    27 days, 17 hours, 17 minutes and 55 seconds
    27 days, 17 hours, 17 minutes and 54 seconds
    27 days, 17 hours, 17 minutes and 53 seconds
    

    希望这是你想要的

    2023-02-12 18:32 回答
撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有