在Java中将时间戳转换为日期
这是我的数据库:
在这里,我必须检查查询当前日期+状态= Q信息并获取计数值。
这是我的代码:
public class TodayQ { public int data() { int count=0; Date date = new Date(timestamp); DateFormat dateFormat = new SimpleDateFormat ("yyyy-MM-dd"); System.out.println( dateFormat.format (date)); // count++; try { Class.forName("com.mysql.jdbc.Driver"); Connection con = DriverManager.getConnection( "jdbc:mysql://localhost:3306/pro", "root", ""); PreparedStatement statement = con .prepareStatement("select * from 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)格式。 现在我得到了输出。 但我希望在我的数据库上使用时间戳。 那么如何在Java中将时间戳转换为日期。 如何在我的代码中使用该代码?
您可以使用mysql函数实现相同的function。 希望以下查询为您提供所需的输出。
select * from orders where status='Q' AND date_format(from_unixtime(date),'%Y-%m-%d') = current_date;
Date date = new Date(timestamp);
而时间戳是一个长变量
假设时间戳是以毫秒为单位的时间,您可以使用java.util.Calendar将时间戳转换为日期时间,如下所示:
java.util.Calendar cal = Calendar.getInstance(); cal.setTimeInMillis(timestamp); java.util.Date date = cal.getTime();
看起来你看到的整数值是自大纪元开始以来的UNIX秒数(即1970-01-01T00:00:00Z) – > http://en.wikipedia.org/wiki/Unix_epoch
我不知道mysql JDBC驱动程序是否会为您转换此字段。 如果是这样,获得其价值的首选方式是:
java.sql.Timestamp ts = result.getTimestamp( columnNumber );
Timestamp扩展了java.util.Date,因此您可以在需要常规java.util.Date的地方使用它。
如果由于某种原因,这不会产生所需的结果,则将列值设置为long
并将值调整为毫秒。 你很幸运,因为Java和UNIX的时代同时开始(Java更精确)。
long ts = result.getLong( columnNumber ) * 1000L; java.util.Date date = new java.util.Date( ts );
以yyyy-mm-dd打印时间戳:
Date date = new Date(timestamp); DateFormat dateFormat = new SimpleDateFormat ("yyyy-MM-dd"); System.out.println( dateFormat.format (date));
UPDATE
这是你如何进行的一个提示:
public static int data() { int count = 0; Date now = Calendar.getInstance().getTime(); System.out.println("TODAY IS:"+now.getTime()); //TODAY IS:1344007864862 try { Class.forName("com.mysql.jdbc.Driver"); Connection con = (Connection) DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", ""); PreparedStatement statement1 = (PreparedStatement) con.prepareStatement("SELECT * FROM ORDERS WHERE STATUS = 'Q' AND DT= "+now.getTime()); ResultSet rs1 = statement1.executeQuery(); while (rs1 .next()) { count++; //A HIT IS FOUND } } catch (Exception exc) { System.out.println(exc.getMessage()); } return count; }
显然,now.getTime()返回在now变量中捕获日期的实际毫秒数。 从现在开始,数学完全取决于你的实施。
请记住,在午夜(10/05/2012 00:00:00)获取Calendar对象的方法是在Java程序中获取没有时间戳的当前日期
数据库中的日期列应为TIMESTAMP
或DATE
或TIME
。
它们分别作为java.sql.Timestamp
或java.sql.Date
或java.sql.Time
检索。
所有这些类都扩展了java.util.Date
。
因此,数据应该已经采用您要求的格式。
所以没有什么可做的。