gpt4 book ai didi

android - 将系统日期和时间与数据库日期和时间分开比较,以开始另一项 Activity

转载 作者:行者123 更新时间:2023-11-29 03:35:57 27 4
gpt4 key购买 nike

这可能是我在 StackOverFlow 中找到的类似问题。但是我的情况与所有人都有点不同。在我的数据库中,我有开始日期和开始时间。我希望系统分别比较它的日期和时间,因为开始日期和时间在数据库中的不同列中。首先,系统比较日期,然后比较时间。仅当日期相同且时间早于数据库中的开始时间 15 分钟时,才应打开另一个 Activity 。到目前为止,我已经这样做了;

private void startTraining() {
Calendar calendar1 = Calendar.getInstance();
SimpleDateFormat formatter = new SimpleDateFormat("MM-dd-yyy");

String currentDate = formatter.format(calendar1.getTime());
System.out.println(currentDate);

Calendar calendar2 = Calendar.getInstance();
SimpleDateFormat formatter2 = new SimpleDateFormat("hh:mm");

String currentTime = formatter2.format(calendar2.getTime());
System.out.println(currentTime);

String trainingStartDate = SharedMemory.getInstance()
.getCurrentTraining().getDate();

String trainingStartTime = SharedMemory.getInstance()
.getCurrentTraining().getStartTime();
int difference = trainingStartTime.compareTo(currentTime);

System.out.println(difference);
//System.out.println(trainingStartTime);


if (currentDate.toString().equals(trainingStartDate)&& difference < 15) {

Log.i("Debug", "CHECKPOINT");
Intent intent = new Intent(getApplicationContext(),
TraineeListActivity.class);
MainActivity.this.startActivity(intent);

finish();
} else{

}

}

我没有得到我期望的结果。提前致谢。

最佳答案

您使用 String.compareTo() 来比较“时间”String,这将无法正常工作。尝试将代码更改为此

private void startTraining() throws ParseException {
// current date & time
Calendar now = Calendar.getInstance();

// parse date & time from database
String trainingStartDate = SharedMemory.getInstance()
.getCurrentTraining().getDate();
String trainingStartTime = SharedMemory.getInstance()
.getCurrentTraining().getStartTime();
String strDateTime = trainingStartDate + " " + trainingStartTime;

Calendar training = Calendar.getInstance();
training.setTime(new SimpleDateFormat("MM-dd-yyyy kk:mm")
.parse(strDateTime));

// find difference in milliseconds
long difference = training.getTimeInMillis() - now.getTimeInMillis();

if (difference < 15 * 60 * 1000) { //less than 15 minutes
Log.i("Debug", "CHECKPOINT");
Intent intent = new Intent(getApplicationContext(),
TraineeListActivity.class);
MainActivity.this.startActivity(intent);

finish();
} else {

}
}

关于android - 将系统日期和时间与数据库日期和时间分开比较,以开始另一项 Activity ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21773081/

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