如何更改查询中的时间格式?

时间:2013-08-18 05:18:30

标签: mysql sql database oracle

我在AliasToBeanResultTransformer的帮助下在Hibernate中使用本机sql查询...如下所示

        List<took> uy = (List<took>) session
.createSQLQuery("SELECT distinct u.name, cast('Not Defined' as VARCHAR2(6)) as  BOA_Type, u.updated_by, u.updateddate FROM took u where u.FLAG='N' order by u.name")
        .addScalar("name",Hibernate.STRING)
        .addScalar("Access_Type",Hibernate.STRING)
        .addScalar("updated_by",Hibernate.STRING)
        .addScalar("updateddate",Hibernate.TIMESTAMP)
        .setResultTransformer(new AliasToBeanResultTransformer(took.class)).list();

现在问题是addScalar("updateddate",Hibernate.TIMESTAMP)和检查我发现列表中的所有对象一样 有这个值

  

2011-01-03 10:10:55.591

但是我希望这个属性的值可以是这种格式..

  

20110817 17:12

(SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd HH:mm");)

现在请告知我如何在查询中设置这种格式本身,以便以后我不必在代码中的任何其他位置进行显式更改,并且我的pojo具有时间戳的这个属性请告知

2 个答案:

答案 0 :(得分:1)

尝试 Oracle

select to_char(sysdate,'yyyyMMdd HH:mi') from dual

在查询中使用此功能

select to_char(yourdatetimefieldname,'yyyyMMdd HH:mi') from yourtablename

对于 Mysql ,你可以这个

SELECT date_format(mydatefield,'%Y%m%d %H%i') as mydatefield FROM mytable

答案 1 :(得分:1)

您可以修改您的查询以在Oracle中阅读:

SELECT 
  distinct u.name, 
  cast('Not Defined' as VARCHAR2(6)) as BOA_Type, 
  u.updated_by,
  to_char(u.updateddate, 'yyyymmdd hh24:mi') as updated
FROM took u 
where 
  u.FLAG='N' 
order by 
  u.name

http://sqlfiddle.com/#!4/9fef46/2

在MySQL中,您的查询将如下所示:

SELECT 
  distinct u.name, 
  cast('Not Defined' as VARCHAR2(6)) as BOA_Type, 
  u.updated_by,
  date_format(u.updateddate, '%Y%m%d %H%i') as updated
FROM took u 
where 
  u.FLAG='N' 
order by 
  u.name

http://sqlfiddle.com/#!2/88fb25/1