有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

hibernate中的java更改日期格式条件查询?

我正在使用下面的查询显示我的测试名称和日期。现在我的日期格式是2014-02-27 17:26:49.0,但我需要以2014-02-27格式显示。如何修改对此的查询

Session ses = sessionFactory.getCurentSession();
Criteria c = ses.createCriteria(user.class);
c.add(Restrictions.eq("id", uid));
c.add(Restrictions.eq("name", uname));

ProjectionList pl = Projections.projectionList();
pl.add(Projections.property("testid"));
pl.add(Projections.property("date"));

c.setProjection(Projections.distinct(pl));
List<String> list = c.list();

共 (4) 个答案

  1. # 1 楼答案

    上面的代码不正确。它选择两个字段,您假设它返回一个List<String>。这是不可能的。列表中的每个元素都是一个对象数组,包含两个元素:testid和date。date元素的类型将与实体中的date字段相同(我希望是java.util.Date

    因此,要使用特定的格式显示查询结果,可以使用以下内容:

    DateFormat df = new SimpleDateFormat("MMMM dd, yyyy");
    List<Object[]> rows = c/list();
    for (Object[] row : rows) { 
        Date date = (Date) row[1];
        System.out.println(row[0] + " - " + df.format(date);
    } 
    
  2. # 2 楼答案

    By using "sqlGroupProjection" I have changed my date format to **2014-02-27**
    
    projectionList.add(Projections.sqlGroupProjection("date(date) as createdDate", "createdDate", new String[] { "createdDate" }, new Type[] { StandardBasicTypes.DATE }));
    
  3. # 3 楼答案

    试试这个

    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd/MM/yyyy hh:mm");
    
        Date inputDate = new Date();
    
        System.out.println(simpleDateFormat.format(inputDate));
    }
    

    输出:

    27/02/2014 07:25
    
  4. # 4 楼答案

            SimpleDateFormat format1 = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
            SimpleDateFormat format2 = new SimpleDateFormat("MMMM dd,yyyy");
            Date date = format1.parse("2014-02-27 17:26:49.00");
            System.out.println(format2.format(date));       
    
    INPUT : 2014-02-27 17:26:49.00
    OUTPUT : February 27,2014