gpt4 book ai didi

java - 从 2 个 TimePicker 获取值并进行比较

转载 作者:行者123 更新时间:2023-12-02 03:52:46 26 4
gpt4 key购买 nike

在我的应用程序中,我在 Activity 中设置了 2 个 TimePicker。这是我目前从 2 个 TimePicker 获取值的方法:

int hour1 = mFirstWakeUpTimePicker.getCurrentHour();
int min1 = mFirstWakeUpTimePicker.getCurrentMinute();
int hour2 = mSecondWakeUpTimePicker.getCurrentHour();
int min2 = mSecondWakeUpTimePicker.getCurrentMinute();

GregorianCalendar calendar1 = new GregorianCalendar();
GregorianCalendar calendar2 = new GregorianCalendar();

calendar1.set(Calendar.HOUR_OF_DAY, hour1);
calendar1.set(Calendar.MINUTE, min1);
calendar2.set(Calendar.HOUR_OF_DAY, hour2);
calendar2.set(Calendar.MINUTE, min2);

之后,我需要比较它们以检查它们是否至少相隔 3 分钟。我该如何实现这一目标?另外,编写这段代码的更好方法是什么?

感谢任何帮助。

最佳答案

假设您希望calendar2比calendar1晚三分钟,您可以在从Timepickers获取小时和分钟后立即这样做:

GregorianCalendar calendar1 = new GregorianCalendar();
GregorianCalendar calendar2 = new GregorianCalendar();

calendar1.set(Calendar.HOUR_OF_DAY, hour1);
calendar1.set(Calendar.MINUTE, min1);
calendar2.set(Calendar.HOUR_OF_DAY, hour2);
calendar2.set(Calendar.MINUTE, min2);

long millisCal1 = calendar1.getTimeInMillis();
long millisCal2 = calendar2.getTimeInMillis();

if (millisCal2 - millisCal1 >= 1000 * 60 * 3){
// They differ of at least three mins
} else {
// They not differ of at least three mins
}

其中三分钟的单位为毫秒 1000 * 60 * 3。如果您想晚于calendar2检查calendar1,只需调换if语句中的顺序即可。

再见

关于java - 从 2 个 TimePicker 获取值并进行比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35742979/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com