0

嗨,我必须在检查查询并返回计数值后将时间戳转换为日期。我的数据库有日期(1344399208,1344399269),状态(Q,Q)。这是我的代码:

public class GetCurrentDateTime {
 public int data(){
int count=0;
java.sql.Timestamp timeStamp =new Timestamp(System.currentTimeMillis());

          java.sql.Date      date      = new java.sql.Date(timeStamp.getTime()); 
           System.out.println(date);
//count++;


try{
    Class.forName("com.mysql.jdbc.Driver");
    Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/xcart-432pro","root","");

    PreparedStatement statement =  con.prepareStatement("select * from xcart_orders where status='Q' AND date=CURDATE()");
     ResultSet result = statement.executeQuery();
     while(result.next()) {
            // Do something with the row returned.
            count++; //if the first col is a count.
        }



}

      catch(Exception exc){
      System.out.println(exc.getMessage());
      }


    return count;
       }

        }

这里日期以时间戳格式保存。但我喜欢转换日期(yyyy-mm-dd)格式。它已成功完成。我得到的输出是 2012-08-08。但我今天必须检查查询日期+ status = Q .so如何将该日期保存在变量中并在查询中调用该变量。so如何为上述条件编写查询。检查条件并在我的tomcat控制台上显示返回计数值。如何做。请帮我

4

2 回答 2

0

To convert date to the date format specified:

int timestamp = 1231342342342; // replace with timestamp fetched from DB
Date date = new Date(timestamp);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-mm-dd");
String dateString = sdf.format(date); //convert to yyyy-mm-dd format

From what I understand from the edit, you want the query to be something like this:

PreparedStatement statement =  con.prepareStatement("select * from xcart_orders where status='Q' AND date='"+dateString+"'");

I'm assuming that the date is stored in string format in the DB since you asked it to be converted into a particular format.

From comments:

To get midnight date:

Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(timestamp);
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);

To get all entries within a 24 period:

"select * from xcart_orders where status='Q' AND date between " + cal.getTimeInMillis() + " and " + (cal.getTimeInMillis() + 86400000l);
于 2012-08-08T04:35:35.310 回答
0

部分回答您的问题

日期示例

从 Code Ranch 和 SO 帖子中借用的示例

// Get system time

Timestamp SysTime = new Timestamp(System.currentTimeMillis());

java.util.Date UtilDate = new java.util.Date(Systime.getTime());
java.sql.Date SQLDate = new java.sql.Date(Systime.getTime());

// Date + Time + Nano Sec
System.out.println(SysTime); 

// Date + Time
System.out.println(UtilDate); 

// Date
System.out.println(SQLDate); 

格式化日期

// Apply Format
Date InDate = SQLDate; // or UtilDate
DateFormat DateFormat = new SimpleDateFormat("yyyy MM dd");
String DisplayDate = DateFormat.format(InDate);
System.out.println(DisplayDate);

请注意,我是 java 新手,因此请验证它是否有效。

比较日期

请参阅此 SO 帖子:

如何使用 Java 比较日期

于 2012-08-08T04:47:47.407 回答