Android倒计时:计算两个时间将得到的时间差转化为倒计时(xx时xx分xx秒格式)

时间:2024-02-17 10:47:26

首先是一个自定义控件:

public class RushBuyCountDownTimerView extends LinearLayout {

    // 小时,十位
    private TextView tv_hour_decade;
    // 小时,个位
    private TextView tv_hour_unit;
    // 分钟,十位
    private TextView tv_min_decade;
    // 分钟,个位
    private TextView tv_min_unit;
    // 秒,十位
    private TextView tv_sec_decade;
    // 秒,个位
    private TextView tv_sec_unit;

    private Context context;

    private int hour_decade;
    private int hour_unit;
    private int min_decade;
    private int min_unit;
    private int sec_decade;
    private int sec_unit;
    // 计时器
    private Timer timer;

    private Handler handler = new Handler() {

        public void handleMessage(Message msg) {
            countDown();
        }

        ;
    };

    public RushBuyCountDownTimerView(Context context, AttributeSet attrs) {
        super(context, attrs);

        this.context = context;
        LayoutInflater inflater = (LayoutInflater) context
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View view = inflater.inflate(R.layout.view_countdowntimer, this);

        tv_hour_decade = (TextView) view.findViewById(R.id.tv_hour_decade);
        tv_hour_unit = (TextView) view.findViewById(R.id.tv_hour_unit);
        tv_min_decade = (TextView) view.findViewById(R.id.tv_min_decade);
        tv_min_unit = (TextView) view.findViewById(R.id.tv_min_unit);
        tv_sec_decade = (TextView) view.findViewById(R.id.tv_sec_decade);
        tv_sec_unit = (TextView) view.findViewById(R.id.tv_sec_unit);

    }

    /**
     * @param
     * @return void
     * @throws
     * @Description: 开始计时
     */
    public void start() {

        if (timer == null) {
            timer = new Timer();
            timer.schedule(new TimerTask() {

                @Override
                public void run() {
                    handler.sendEmptyMessage(0);
                }
            }, 0, 1000);
        }
    }

    /**
     * @param
     * @return void
     * @throws
     * @Description: 停止计时
     */
    public void stop() {
        if (timer != null) {
            timer.cancel();
            timer = null;
            tv_hour_decade.setText(0 + "");
            tv_hour_unit.setText(0 + "");
            tv_min_decade.setText(0 + "");
            tv_min_unit.setText(0 + "");
            tv_sec_decade.setText(0 + "");
            tv_sec_unit.setText(0 + "");
        }
    }

    /**
     * @param
     * @return void
     * @throws Exception
     * @throws
     * @Description: 设置倒计时的时长
     */
    public void setTime(String hour, String min, String sec) {

        int Hour = Integer.parseInt(hour);
        int Min = Integer.parseInt(min);
        int Second = Integer.parseInt(sec);

        if (Hour >= 120 || Min >= 60 || Second >= 60 || Hour < 0 || Min < 0
                || Second < 0) {
            throw new RuntimeException("error:check your time");
        }

        hour_decade = Hour / 10;
        hour_unit = Hour - hour_decade * 10;

        min_decade = Min / 10;
        min_unit = Min - min_decade * 10;

        sec_decade = Second / 10;
        sec_unit = Second - sec_decade * 10;

        tv_hour_decade.setText(hour_decade + "");
        tv_hour_unit.setText(hour_unit + "");
        tv_min_decade.setText(min_decade + "");
        tv_min_unit.setText(min_unit + "");
        tv_sec_decade.setText(sec_decade + "");
        tv_sec_unit.setText(sec_unit + "");

    }

    /**
     * @param
     * @return boolean
     * @throws
     * @Description: 倒计时
     */
    private void countDown() {

        if (isCarry4Unit(tv_sec_unit)) {
            if (isCarry4Decade(tv_sec_decade)) {

                if (isCarry4Unit(tv_min_unit)) {
                    if (isCarry4Decade(tv_min_decade)) {

                        if (isCarry4Unit(tv_hour_unit)) {
                            if (isCarry4Decade(tv_hour_decade)) {
                                // ToastUtil.safeShowToast(TLApplication.mContext, "Time limited");
                                stop();
                            }
                        }
                    }
                }
            }
        }
    }

    /**
     * @param
     * @return boolean
     * @throws
     * @Description: 变化十位,并判断是否需要进位
     */
    private boolean isCarry4Decade(TextView tv) {

        int time = Integer.valueOf(tv.getText().toString());
        time = time - 1;
        if (time < 0) {
            time = 5;
            tv.setText(time + "");
            return true;
        } else {
            tv.setText(time + "");
            return false;
        }

    }

    /**
     * @param
     * @return boolean
     * @throws
     * @Description: 变化个位,并判断是否需要进位
     */
    private boolean isCarry4Unit(TextView tv) {

        int time = Integer.valueOf(tv.getText().toString());
        time = time - 1;
        if (time < 0) {
            time = 9;
            tv.setText(time + "");
            return true;
        } else {
            tv.setText(time + "");
            return false;
        }

    }
}
view_countdowntimer.xml:
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:background="#FF0000"
    android:padding="5dp">

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content">


        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:gravity="center"
            android:text="倒计时:"
            android:textColor="#FFFFFF" />

        <TextView
            android:id="@+id/tv_hour_decade"
            style="@style/RushBuyCountDownTimerViewStyle" />

        <TextView
            android:id="@+id/tv_hour_unit"
            style="@style/RushBuyCountDownTimerViewStyle"
            android:layout_marginLeft="1dp" />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:gravity="center"
            android:text="时"
            android:textColor="#FFFFFF"
            android:textSize="16sp" />

        <TextView
            android:id="@+id/tv_min_decade"
            style="@style/RushBuyCountDownTimerViewStyle" />

        <TextView
            android:id="@+id/tv_min_unit"
            style="@style/RushBuyCountDownTimerViewStyle"
            android:layout_marginLeft="1dp" />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:gravity="center"
            android:text="分"
            android:textColor="#FFFFFF"
            android:textSize="16sp" />

        <TextView
            android:id="@+id/tv_sec_decade"
            style="@style/RushBuyCountDownTimerViewStyle" />

        <TextView
            android:id="@+id/tv_sec_unit"
            style="@style/RushBuyCountDownTimerViewStyle"
            android:layout_marginLeft="1dp" />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:gravity="center"
            android:text="秒"
            android:textColor="#FFFFFF"
            android:textSize="16sp" />

    </LinearLayout>

</FrameLayout>
RushBuyCountDownTimerViewStyle:
<style name="RushBuyCountDownTimerViewStyle">
        <item name="android:layout_width">wrap_content</item>
        <item name="android:layout_height">wrap_content</item>
        <item name="android:gravity">center</item>
        <item name="android:text">0</item>
        <item name="android:textColor">#FFFFFF</item>
        <item name="android:textSize">16sp</item>

可能用到的时间格式转换工具:

/** 将格林威治时间格式转为指定的时间格式 */
    public static String GTMToLocal(String GTMDate) {

        int tIndex = GTMDate.indexOf("T");
        String dateTemp = GTMDate.substring(0, tIndex);
        String timeTemp = GTMDate.substring(tIndex + 1, GTMDate.length() - 6);
        String convertString = dateTemp + " " + timeTemp;

        SimpleDateFormat format;
        format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.ENGLISH);
        Date result_date;
        long result_time = 0;

        if (null == GTMDate) {
            return GTMDate;
        } else {
            try {
                format.setTimeZone(TimeZone.getTimeZone("GMT00:00"));
                result_date = format.parse(convertString);
                result_time = result_date.getTime();
                format.setTimeZone(TimeZone.getDefault());
                return format.format(result_time);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return GTMDate;

    }

设置倒计时:

String startTime = StringUtil.GTMToLocal("2015-12-28T12:49:13.45425+08:00");
        String endTime = StringUtil.GTMToLocal("2015-12-31T00:17:13.45425+08:00");

        DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        try {
            Date d1 = df.parse(startTime);
            Date d2 = df.parse(endTime);
            long diff = d2.getTime() - d1.getTime(); // mslong days = diff / (1000 * 60 * 60 * 24);
            long hours = (diff - days * (1000 * 60 * 60 * 24)) / (1000 * 60 * 60);
            long minutes = (diff - days * (1000 * 60 * 60 * 24) - hours * (1000 * 60 * 60)) / (1000 * 60);
            long second = (diff / 1000 - days * 24 * 60 * 60 - hours * 60 * 60 - minutes * 60);

            hours += days * 24;

// RushBuyCountDownTimerView
timerView; 需要初始化timerView

            timerView.setTime(hours + "", minutes + "", second + "");
            timerView.start();

        } catch (Exception e) {
            e.printStackTrace();
        }