1

我正在开发一个简单的销售点系统,并试图生成尽可能多的销售和费用数据统计信息。我想要一种方法来显示本周的销售情况,但是,尽管我浏览了 api 并检查了一些教程,但我真的找不到方法。最后,我决定比较一下今天DAY_OF_WEEK_IN_MONTH发生的交易DAY_OF_WEEK_IN_MONTH。例如,如果它们相同,则交易必须与今天在同一周发生,即本周。起初,它似乎有效,但现在又重新考虑了。如果有人向我指出正确的方法,我将不胜感激。

public void getSalesTotalForWeek() throws SQLException {
    //getDatesCount() populates a collection(listDates) with dates in which
    //transactions took place
    getDatesCount();
    //sets cal with today's date
    Calendar cal = new GregorianCalendar();
    for (int i = 0; i < listDates.size(); i++) {
        //set c with the date of when the transaction took place
        Calendar c = new GregorianCalendar(Integer.parseInt(listDates.get(i).substring(0, 4)),
        Integer.parseInt(listDates.get(i).substring(5, 7)), Integer.parseInt(listDates.get(i).substring(8, 10)));
        //This is like saying if the day of week in month when the transaction took place
        //is the same as that of today, then the transaction
        //must have taken place in the same week as today
        if(cal.get(Calendar.DAY_OF_WEEK_IN_MONTH) == c.get(Calendar.DAY_OF_WEEK_IN_MONTH)){
            rst = stmt.executeQuery("SELECT * FROM transaction_history where Time like '"+   listDates.get(i) + "%'");
            while (rst.next()) {
                weekSalesTotal += rst.getInt(2);
            }
        }
    }
}
4

1 回答 1

1

您的代码中有几处需要修复:

public void getSalesTotalForWeek()

命名的方法get*()并没有真正返回任何东西(违反直觉)。似乎weekSalesTotal是一个领域,记住线程安全。


Calendar cal = new GregorianCalendar();

如果有一天有人问你上周的销售额怎么办?还是三月的第一周?考虑将开始日期和结束日期都作为参数传递。您还确定要使用服务器默认时区吗?


Calendar c = new GregorianCalendar(Integer.parseInt(listDates.get(i).substring(0, 4)),
Integer.parseInt(listDates.get(i).substring(5, 7)), Integer.parseInt(listDates.get(i).substring(8, 10)));

listDates是一个List<String>?请考虑Date类型,上面的代码看起来很糟糕。


cal.get(Calendar.DAY_OF_WEEK_IN_MONTH) == c.get(Calendar.DAY_OF_WEEK_IN_MONTH)

我不太明白这个代码。我正在阅读的JavaDoc,DAY_OF_WEEK_IN_MONTH但我仍然不明白......


"SELECT * FROM transaction_history where Time like '"+   listDates.get(i) + "%'"

如果您只对第二个(我们称之为value)感兴趣,请不要选择所有列。也不要连接 SQL,SQL 注入已经在路上了。最后使用like运算符进行日期吗?您DATE在数据库中使用正确的类型吗?


weekSalesTotal场吗?记住同步。并避免在循环中运行 SQL。

TL;博士

我相信你的整个方法可以用更强大、更快、更简单的东西代替:

public int getSalesTotalWithin(Date start, Date end) {
  rst = stmt.executeQuery(
    "SELECT SUM(value) FROM transaction_history where Time BETWEEN ? AND ?");
  return rst.getInt(1);
}

这只是伪代码,它缺少 JDBC 样板和?替换。但你会明白的。现在您可以使用任何日期范围调用它,例如:

Calendar weekAgo = new GregorianCalendar();
weekAgo.add(Calendar.DATE, -7);
getSalesTotalWithin(weekAgo.getTime(), new Date());

如果您想要自上周一以来的统计数据:

Calendar lastMonday = new GregorianCalendar(TimeZone.getTimeZone("GMT"));
lastMonday.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
lastMonday.set(Calendar.HOUR_OF_DAY, 0);
//...zero other fields
getSalesTotalWithin(lastMonday.getTime(), new Date());
于 2012-11-10T18:39:53.717 回答