简体   繁体   中英

How do I get time picked by timepicker in milliseconds and compare time difference between the two time pickers in android?

I have looked into numerous examples and tried this way, but it is not getting me the correct output. Any help is highly appreciated. Thanks, Any correction in the code or a new code is highly appreciated. With all the knowledge I have I tried in the following way, I have also tried in SimpleDateFormat function but it ended up taking 1970 jan 1st every time I picked time.

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;
    String timex;
    String timey;
    long timeyy;
    long timexx;

    @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);
                        Calendar c3 = Calendar.getInstance();
                        c3.set(Calendar.HOUR_OF_DAY, hourOfDay1);
                        c3.set(Calendar.MINUTE, minute1);
                        timeyy = c3.getTimeInMillis();
                    }
                },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);
                        Calendar c2 = Calendar.getInstance();
                        c2.set(Calendar.HOUR_OF_DAY, hourOfDay);
                        c2.set(Calendar.MINUTE, minute);
                        timexx = c2.getTimeInMillis();
                    }
                },hour,mins,true);
                time2.show();
            }
        });
        b1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                long difference = timexx - timeyy;
                long minutesdifference = difference / 60000;
                Log.d("Result", String.valueOf(minutesdifference))
                
               
            }
        });
    }
}

When am trying to find the difference between two time pickers within the same day. It is resulting me the desired output, ie difference between 10:55 and 11:55 gives me 60 minutes. When my time falls in the other day it is giving me negative answer. ie 23:52 and 00:00 is giving me -1431.

java.time

Use java.time, the modern Java date and time API, for your time work. While I cannot tell why your code didn't work, the following boiled-down example does.

Edit: now taking into account that timexx may be on the following day

    LocalTime timeyy;
    LocalTime timexx;
    
    int hourOfDay1 = 23;
    int minute1 = 52;
    timeyy = LocalTime.of(hourOfDay1, minute1);
    
    int hourOfDay = 0;
    int minute = 0;
    timexx = LocalTime.of(hourOfDay, minute);
    
    long minutesdifference = ChronoUnit.MINUTES.between(timeyy, timexx);
    if (minutesdifference < 0) { // timexx is the following day; add 1 day
        minutesdifference += Duration.ofDays(1).toMinutes(); 
    }
    System.out.println("Result: " + minutesdifference + " minutes");

Output is:

Result: 8 minutes

You may also want to look into using the Duration class. There's a link further down.

Question: Doesn't java.time require Android API level 26?

java.time works nicely on both older and newer Android devices. It just requires at least Java 6 .

  • In Java 8 and later and on newer Android devices (from API level 26) the modern API comes built-in.
  • In non-Android Java 6 and 7 get the ThreeTen Backport, the backport of the modern classes (ThreeTen for JSR 310; see the links at the bottom).
  • On older Android either use desugaring or the Android edition of ThreeTen Backport. It's called ThreeTenABP. In the latter case make sure you import the date and time classes from org.threeten.bp with subpackages.

Links

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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