如何在java中获取当前日期详细信息?我开发了一个课程:
public class RetailerWs {
public String customerData(){
String customerInfo = "";
try{
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/pro","root","");
//Find customer information where the customer ID is maximum
PreparedStatement statement = con.prepareStatement("select * from orders where status='Q' AND date='2012-08-01'");
ResultSet result = statement.executeQuery();
int count=0;
count++;
// System.out.println(count);
while(result.next()){
System.out.println(count);
}
}
catch(Exception exc){
System.out.println(exc.getMessage());
}
return customerInfo;
}
}
这是另一个班级。
public class Demo {
public static void main(String[] args){
RetailerWs obj = new RetailerWs();
System.out.println(obj.customerData());
}
}
如果我运行demo
,则会调用RetailerWs
,然后显示count
的值。问题是目前我手动插入日期,即
PreparedStatement statement = con.prepareStatement("select * from orders where status='Q' AND date='2012-08-01'");
但我想要一个获取当前日期的查询。我该如何创建和调用它?请帮我。
答案 0 :(得分:4)
你可以尝试
select * from orders where status='Q' AND date = CURDATE();
答案 1 :(得分:1)
您可以使用calendar实现它:
public static Date getToday(Date date) {
Calendar c = Calendar.getInstance();
c.setTime(date);
c.set(Calendar.HOUR_OF_DAY, 0);
c.set(Calendar.MINUTE, 0);
c.set(Calendar.SECOND, 0);
c.set(Calendar.MILLISECOND, 0);
return c.getTime();
}
答案 2 :(得分:1)
用问号替换预备语句中的日期,并使用setDate()
方法设置其值:
statement = con.prepareStatement("select * from orders where status='Q' AND date=?");
statement.setDate(1, new Date());
setDate()
的第一个参数是?
的索引(从1开始)。将此机制用于其他参数(Q)也是一种好习惯。
答案 3 :(得分:0)
如果日期列包含时间部分,则需要修改如下所示的查询
select * from orders where status='Q' AND
date >= CURDATE() and date<CURDATE() +interval 1 day ;