tl;博士
String sql = // Create the text of your SQL statement to be executed.
"SELECT SUM( number_col ) FROM tbl WHERE date_col <= '" // Include the name of the date column to be compared. Should be part of your string literal.
+ LocalDate.now( ZoneId.of( "Pacific/Auckland" ) ) // Capture the current date per the wall-clock time used by the people of a particular region (a time zone).
.toString() // Generate a string in standard ISO 8601 to represent the value of this `LocalDate` value.
+ "' ;" // A proper SQL statement is terminated with a semicolon. Omitted from the Question’s example code.
;
java.time
现代方法使用 java.time 类取代了麻烦的遗留类 Date、Calendar 和 SimpleDateFormat。
您的评论说您在 SQLite 中将仅日期值存储为标准 ISO 8601 格式的文本:YYYY-MM-DD。
对于 Java 中的仅日期值,请使用 LocalDate 类。 LocalDate 类表示没有时间和时区的仅日期值。
时区对于确定日期至关重要。对于任何给定的时刻,日期在全球范围内因区域而异。例如,Paris France 中午夜后几分钟是新的一天,而 Montréal Québec 中仍然是“昨天”。
如果没有指定时区,JVM 会隐式应用其当前的默认时区。该默认值可能随时更改,因此您的结果可能会有所不同。最好将您想要/预期的时区明确指定为参数。
以continent/region 的格式指定proper time zone name,例如America/Montreal、Africa/Casablanca 或Pacific/Auckland。切勿使用 3-4 个字母的缩写,例如 EST 或 IST,因为它们不是真正的时区,没有标准化,甚至不是唯一的 (!)。
ZoneId z = ZoneId.of( "America/Montreal" ) ;
LocalDate today = LocalDate.now( z ) ;
如果你想使用 JVM 当前的默认时区,请求它并作为参数传递。如果省略,则隐式应用 JVM 的当前默认值。最好是明确的,因为默认值可能会在任何时候在运行时被 JVM 中任何应用程序的任何线程中的任何代码更改。
ZoneId z = ZoneId.systemDefault() ; // Get JVM’s current default time zone.
或者指定一个日期。您可以通过数字设置月份,1 月至 12 月的编号为 1-12。
LocalDate ld = LocalDate.of( 1986 , 2 , 23 ) ; // Years use sane direct numbering (1986 means year 1986). Months use sane numbering, 1-12 for January-December.
或者,更好的是,使用预定义的Month 枚举对象,一年中的每个月一个。提示:在整个代码库中使用这些 Month 对象,而不是仅仅使用整数,以使您的代码更具自记录性、确保有效值并提供 type-safety。
LocalDate ld = LocalDate.of( 1986 , Month.FEBRUARY , 23 ) ;
只需调用toString即可生成标准格式的字符串。
String dateText = LocalDate.now( z ).toString() ;
添加到您的 SQL 字符串。您的 SQL 字符串不正确,因为列的 name 应该是 SQL 文本的一部分。它应该是您的字符串文字的一部分,但您排除了这在 Java 的上下文中没有意义。
String sql = "SELECT SUM( number_col ) FROM tbl WHERE date_col <= '" + dateText + "' ;" ;
这会呈现一个字符串,例如:
SELECT SUM( number_col ) FROM tbl WHERE when_col <= '2018-01-23' ;
关于java.time
java.time 框架内置于 Java 8 及更高版本中。这些类取代了麻烦的旧 legacy 日期时间类,例如 java.util.Date、Calendar 和 SimpleDateFormat。
Joda-Time 项目现在位于maintenance mode,建议迁移到java.time 类。
要了解更多信息,请参阅Oracle Tutorial。并在 Stack Overflow 上搜索许多示例和解释。规格为JSR 310。
您可以直接与您的数据库交换 java.time 对象。使用符合JDBC 4.2 或更高版本的JDBC driver。不需要字符串,不需要java.sql.* 类。
从哪里获得 java.time 类?