简体   繁体   English

如何以毫秒为单位获取 timepicker 选择的时间并比较 android 中两个时间选择器之间的时间差?

[英]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.我查看了许多示例并尝试了这种方式,但它没有让我得到正确的 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.凭借我通过以下方式尝试过的所有知识,我也尝试过 SimpleDateFormat function 但每次我选择时间时它最终都会花费 1970 年 1 月 1 日。

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.这是我想要的 output,即 10:55 和 11:55 之间的差异给了我 60 分钟。 When my time falls in the other day it is giving me negative answer.当我的时间落在前几天时,它给了我否定的答案。 ie 23:52 and 00:00 is giving me -1431.即 23:52 和 00:00 给我 -1431。

java.time java.time

Use java.time, the modern Java date and time API, for your time work.使用 java.time,现代 Java 日期和时间 API,为您的时间工作。 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编辑:现在考虑到timexx可能在第二天

    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: Output 是:

Result: 8 minutes结果:8分钟

You may also want to look into using the Duration class.您可能还想考虑使用Duration class。 There's a link further down.下面有一个链接。

Question: Doesn't java.time require Android API level 26?问:java.time不需要Android API 26级吗?

java.time works nicely on both older and newer Android devices. java.time 适用于较旧和较新的 Android 设备。 It just requires at least Java 6 .它只需要至少Java 6

  • In Java 8 and later and on newer Android devices (from API level 26) the modern API comes built-in.在 Java 8 及更高版本以及更新的 Android 设备(来自 API 级别 26)中,现代 ZDB9734A 内置23871083ACE16。
  • 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).在非 Android Java 6 和 7 中,获得 ThreeTen Backport,现代类的后向端口(JSR 310 的 ThreeTen;参见底部的链接)。
  • On older Android either use desugaring or the Android edition of ThreeTen Backport.在较旧的 Android 上,要么使用去糖,要么使用 ThreeTen Backport 的 Android 版本。 It's called ThreeTenABP.它被称为 ThreeTenABP。 In the latter case make sure you import the date and time classes from org.threeten.bp with subpackages.在后一种情况下,请确保从带有子包的org.threeten.bp导入日期和时间类。

Links链接

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

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