将系统日期和时间与数据库日期和时间分开比较以启动另一个活动

时间:2014-02-14 07:17:09

标签: android mysql date

这可能是我在StackOverFlow中发现的类似问题。但是我和他们所有人的情况有点不同。在我的数据库中,我有开始日期和开始时间。我希望系统分别比较它的日期和时间,因为开始日期和时间在数据库中的单独列中。首先,系统比较日期和时间。另一个活动应该仅在日期相同且时间在数据库中的开始时间15分钟之前打开。 到目前为止我已经这样做了;

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{

    }

}

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

1 个答案:

答案 0 :(得分:0)

您使用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 {

    }
}