我在java中创建了两个方法,其中一个返回数据库服务器时间,另一个返回数据库服务器一小时前的时间。现在我必须将这两个日期时间用于sql查询。检索数据库的代码服务器时间是:-
public String database_Time() throws SQLException
{
con = getConnection();
String sql = "select GETDATE()";
clstmt = con.prepareCall(sql);
clstmt.execute();
rs = clstmt.getResultSet();
while(rs.next()) {
timestr= rs.getString(1);
}
System.out.println("database time is" +timestr);
return timestr;
}
另一种检索一小时前时间的方法是
public String previostime() throws ParseException, SQLException
{
database_Time();
String format = "yyyy-MM-dd HH:mm:ss";
SimpleDateFormat simpleDateFormat = new SimpleDateFormat(format);
Date date = simpleDateFormat.parse(timestr);
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
int hours = calendar.get(Calendar.HOUR_OF_DAY);
hours--;
calendar.set(Calendar.HOUR_OF_DAY, hours);
fixedDate = calendar.getTime();
stringDate = simpleDateFormat.format(fixedDate );
System.out.println("previous date is"+(stringDate));
System.out.println("current date is"+timestr);
return stringDate;
}
但是当我在 sql 查询中使用 stringDate 和 timestr 时,出现错误 com.microsoft.sqlserver.jdbc.SQLServerException: 从字符串转换日期和/或时间时转换失败。
sql查询的代码是:-
String sql = "select * from vs1_bag where logtime between 'stringDate' and 'timestr' ";
编辑:- 我检索时间并在我的应用程序中使用它的方法是:-
public String [] getChartTime() throws SQLException, ParseException
{
List<String> tStr = new ArrayList<String>();
database_Time();
String atime[] = null;
previostime();
getConnection();
try
{
con = getConnection();
stmt = con.createStatement();
String sql = "select * from vs1_bag where logtime between 'stringDate'and 'timestr' ";
stmt.executeQuery(sql);
rs = stmt.getResultSet();
while(rs.next()) {
// Just get the value of the column, and add it to the list
tStr.add(rs.getString(1).substring(11,16));
}
}
catch( Exception e )
{
System.out.println("\nException in Bean in getDbTable(String code):"+e);
}
finally
{
closeConnection();
}
// I would return the list here, but let's convert it to an array
atime= tStr.toArray(new String[tStr.size()]);
return atime;
}
如何解决。
最佳答案
不应该是这样吗? :
String sql = "select * from vs1_bag where logtime between '"+stringDate+"' and '"+timestr+"' ";
关于java - java中字符串转换日期或时间时转换失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27241848/