有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java正确的时间格式

我写了一个倒计时计时器,我为它设置了时间,当我显示时间时,它的设置时间+1,我怎么能更正它呢?这是我的代码

    SimpleDateFormat dateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");   
    future=dateFormat.parse("2018-09-25 15:00:00");   
    Date now=new Date();

    if (!now.after(future)) {
        long diff = future.getTime() - now.getTime();
        long days = diff / (24 * 60 * 60 * 1000);
        diff -= days * (24 * 60 * 60 * 1000);
        long hours = diff / (60 * 60 * 1000);
        diff -= hours *( 60 * 60 * 1000);
    }

。。。。。。 例如,如果从1天13:00:00开始计数,则从14开始计数


共 (1) 个答案

  1. # 1 楼答案

    希望这能帮你把时间转换成毫秒。。 你所要做的就是使用定时器。更新标签中剩余的时间。 下面是将dateTimet转换为毫秒的示例代码

    String myDate = "2014/10/29 18:10:45";
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
    Date date = sdf.parse(myDate);
    long millis = date.getTime();
    
    
                CountDownTimer    countDownTimer = new CountDownTimer(millis , 1000) {
                            @Override
                            public void onTick(long millisUntilFinished) {
    
                                if (getActivity() != null && !getActivity().isFinishing()) {
                                    expiryLabel.setText(getResources().getString(R.string.expiresIn,
                                            " " +formatTime(millisUntilFinished));
                                }
                            }
    
                            @Override
                            public void onFinish() {
    
                                if (getActivity() != null && !getActivity().isFinishing()) {
    
                                // do what ever you want
                                }
                            }
                        };
                        countDownTimer.start();
    
                    }
    
    
    
    
     public static String formatTime(long millis) {
            String output = "00:00:00";
            long seconds = millis / 1000;
            long minutes = seconds / 60;
            long hours = minutes / 60;
    
            seconds = seconds % 60;
            minutes = minutes % 60;
            hours = hours % 60;
    
            String secondsD = String.valueOf(seconds);
            String minutesD = String.valueOf(minutes);
            String hoursD = String.valueOf(hours);
    
            if (seconds < 10)
                secondsD = "0" + seconds;
            if (minutes < 10)
                minutesD = "0" + minutes;
            if (hours < 10)
                hoursD = "0" + hours;
    
            output = hoursD + ":" + minutesD + ":" + secondsD;
    
    
    
            return output;
        }