日期和日期格式计算Android

Date and Date format Calculation Android

我有一个日期计算函数。它将我已经检索到的数据库和我正在传递的输入进行比较。调试时,它在 for 循环内分配后显示错误的日期。(输入和数据库日期)下面我用图像显示了示例。

函数代码:

/*String[] veh - vehicle name, String[] from - table from date array,
 * String[] to - table to date array,String from1 - input from date, String to1 - input to date*/
private List getDateComparison(String[] veh, String[] from, String[] to,String from1, String to1) throws ParseException {
    SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:MM",Locale.ENGLISH);
    Date table_from,table_to,input_from,input_to;
    long diff=0,diff1=0,diff2=0,diff3=0;
    int count=0,county=0;;

    for(int i=0;i<veh.length;i++){
        table_from=df.parse(from[i]);
        table_to=df.parse(to[i]);
        input_from=df.parse(from1);
        input_to=df.parse(to1);
        table_from=df.parse(df.format(table_from));
        table_to=df.parse(df.format(table_to));
        input_from=df.parse(df.format(input_from));
        input_to=df.parse(df.format(input_to));
        diff=table_from.getTime()-input_from.getTime();
        diff1=table_from.getTime()-input_to.getTime();
        diff2=input_from.getTime()-table_to.getTime();
        diff3=input_to.getTime()-table_to.getTime();
        if((diff > 0 && diff1>0) || (diff2 > 0 && diff3>0)){
            count++;
            removeAndAddList(veh[i],1);
            Log.d("Date", " ok with from");
        }
        else {
            county = 100;
            removeAndAddList(veh[i],2);
        }
    }
    return vehic;//= veh[0];
}

调试时的函数截图:

已编辑:

在我使用日期格式之前,

SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd",Locale.ENGLISH);

当时计算非常完美。现在它在日期格式上出现了一些问题。我认为我的日期格式在 for 循环中做错了什么。在使用日期格式分配日期后,它显示了更大的日期。我哪里做错了?

您为 SDF 使用的格式不正确

SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:MM",Locale.ENGLISH);

as M 表示 一年中的月份 而您将其用作分钟。

改为HH:mm ... = new SimpleDateFormat("yyyy-MM-dd HH:mm",Locale.ENGLISH);

题外话: 您可以使用 after()before() 方法代替 diff=table_from.getTime()-input_from.getTime(); Date

您可以按以下方式比较日期(来自您的代码):

if((diff > 0 && diff1>0) || (diff2 > 0 && diff3>0)){

将是:

if((table_from.after(input_from) && table_from.after(input_to)) 
|| (input_from.after(table_to) && input_to.after(table_to))){

现在您可以从代码中删除所有 getTime() 减法行(4 行)