Display Data Based on Date

不羁岁月 提交于 2019-12-25 00:58:29

问题


I have 2 columns in a table in mysql which looks sometime like below,

 title    timestamp
--------------------
 test1     1/7/2012
 test2     1/7/2012
 test3     1/7/2012
 test4     2/7/2012
 test5     3/7/2012.

The result I am looking for is something like,

**1/7/2012**
   test1
   test3
**2/7/2012**
   test4
 **3/7/2012**
   test5

Can someone help him here.can this be done just with MySQL query or I need to iterate the resultset in server side and then format the resultset for displaying.


回答1:


You can use a query like this one:

select title,timestamp,str_to_date(timestamp, '%d/%m/%Y') as date from table_name order by date,title;

iterating over the result set and printing the timestamp only when it changes.

str_to_date is a MySQL function which converts a string to a date, useful for sorting. If you are not using MySQL, you should check for an analogous function.




回答2:


If I understood correctly what you want, the code should look like this:

int itemsInPage = 100; //Number of item to display in page
int currentPage = 1; //Index of current page, starting from 1

PreparedStatement ps = con.prepareStatement("select title,timestamp,str_to_date(timestamp,'%d/%m/%Y') as date from table_name order by date,title limit " + ((currentPage - 1) * itemsInPage) + ", " + itemsInPage);

ResultSet rs = ps.executeQuery();

String prevTimestamp = null;

while(rs.next()) {
    if (prevTimestamp == null || !prevTimestamp.equals(rs.getString(2))) {
        System.out.println("*** "+rs.getString(1)+" ***");
    }
    System.out.println(rs.getString(1));
    prevTimestamp = rs.getString(2);
}

If you are coding in a jsp, you should use

out.print(...);

instead of

System.out.println


来源:https://stackoverflow.com/questions/11484680/display-data-based-on-date

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!