简体   繁体   English

如何计算 android 中两个时间选择器之间的时间差?

[英]How do I calculate time difference between two time pickers in android?

I am able to find out the difference between two time intervals, but when the time 1st 12:00am or 00:00 and 2nd time is any other time, I am not getting accurate difference.我能够找出两个时间间隔之间的差异,但是当第 1 次 12:00 或 00:00 和第 2 次是任何其他时间时,我没有得到准确的差异。 Instead I am getting a negative difference.相反,我得到了负面的差异。 Upon debugging I figured out the time is actually taking of the year 1970 January.经过调试,我发现时间实际上是 1970 年 1 月。 I am unable to correct it by taking today's time and calculate the difference.我无法通过今天的时间来纠正它并计算差异。

package com.cksapp.memoryin;

import androidx.appcompat.app.AppCompatActivity;

import android.app.TimePickerDialog;
import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;

import com.google.firebase.Timestamp;
import com.google.firebase.firestore.FirebaseFirestore;
import com.google.firebase.firestore.FirebaseFirestoreSettings;

import java.security.CodeSigner;
import java.sql.Time;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
//import java.util.Date;

public class HourlyCalculator extends AppCompatActivity {
    EditText wage;
    TextView t1, t2, t3;
    ImageView i1, i2;
    Button b1;
    int minutestotal;
    String timex, timey;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.calculator_hourly);
        wage = findViewById(R.id.hourlyrate);
        t1 = findViewById(R.id.starttimetext);
        t2 = findViewById(R.id.endtimetext);
        t3 = findViewById(R.id.finaltime);
        i1 = findViewById(R.id.startimage);
        i2 = findViewById(R.id.endimage);
        b1 = findViewById(R.id.calculatebutton);


        Calendar c = Calendar.getInstance();

        final int hour = c.get(Calendar.HOUR_OF_DAY);
        final int mins = c.get(Calendar.MINUTE);

        i1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                final TimePickerDialog time = new TimePickerDialog(HourlyCalculator.this, new TimePickerDialog.OnTimeSetListener() {
                    @Override
                    public void onTimeSet(TimePicker view, int hourOfDay1, int minute1) {
                        timex = hourOfDay1 + ":" + minute1;
                        t1.setText(timex);
                        Log.d("Time1", timex);
                    }
                },hour, mins, true);
                time.show();
            }
        });

       i2.setOnClickListener(new View.OnClickListener() {
           @Override
           public void onClick(View v) {
               final TimePickerDialog time2 = new TimePickerDialog(HourlyCalculator.this, new TimePickerDialog.OnTimeSetListener() {
                   @Override
                   public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
                       timey = hourOfDay + ":" + minute;
                       t2.setText(timey);
                       Log.d("Time1", timey);
                   }
               },hour,mins,true);
               time2.show();
           }
       });
       b1.setOnClickListener(new View.OnClickListener() {
           @Override
           public void onClick(View v) {
               SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
               try {
                   Date a = sdf.parse(timex);
                   Date b = sdf.parse(timey);
                   long difference = a.getTime() - b.getTime();
                   Log.d("Time", String.valueOf(difference));
                  /* minutestotal = (int) (difference/60000);
                   Log.d("Timearey", String.valueOf(minutestotal));
                   int totalwageinitital = Integer.parseInt(wage.getText().toString());
                  double totalwagepermin = totalwageinitital/60;
                  double finalprice = minutestotal * totalwagepermin;

                   t3.setText(String.valueOf(finalprice));*/
               } catch (ParseException e) {
                   e.printStackTrace();
               }
           }
       });
    }
}

You are parsing the time using only hours and minutes, without providing the year, month and day the sdf will assume Jan 1st, 1970.您仅使用小时和分钟解析时间,而没有提供 sdf 将假定为 1970 年 1 月 1 日的年、月和日。

You should do this in a different way: initialize a calendar object for each date using Calendar.getInstance(), this will give you an instance with today's date, then set the hours and minutes for those 2 instances according to the hours and minutes in the picker and check the difference between their timeInMilliseconds.您应该以不同的方式执行此操作:使用 Calendar.getInstance() 为每个日期初始化日历 object,这将为您提供一个具有今天日期的实例,然后根据中的小时和分钟设置这两个实例的小时和分钟选择器并检查它们的 timeInMilliseconds 之间的差异。

Calendar time = Calendar.getInstance();
time.set(Calendar.HOUR_OF_DAY, hour);
time.set(Calendar.MINUTE, minute);

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

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