【问题标题】:giving the wrong result when date format is changed更改日期格式时给出错误结果
【发布时间】:2017-05-23 21:16:23
【问题描述】:

我正在使用 PostgreSQL。我正在执行一个返回表中最新和旧日期的查询。目前显示结果为YYYY-MM-DD格式,我希望结果显示为MM/DD/YYYY格式。

以下是我的查询:

select min(daterange) as minDate,
       max(daterange) as maxDate 
from   (SELECT to_date(table1.daterange, 'DD/MM/YYYY') as daterange 
        FROM   table1, table2 
        where  table1.sid = table2.sid) tt;

请指教。 table1 中的 daterange 列是字符类型不同。我不能使用 ::date 转换为日期类型,因为我需要在我的 java hibernate 代码中使用此查询,而 java 代码无法识别 ::。 我尝试使用 to_char 和 to_date 但显示的结果是错误的日期。请找到演示here

select min(daterange) as min_cf, 
       max(daterange) as max_cf
from   (select to_char(to_date(table1.daterange, 'DD/MM/YYYY'),'MM/DD/YYYY') as daterange 
        from   table1, table2 
        where table1.sid = table2.sid) tt;

【问题讨论】:

  • 顺便说一句,您可以使用 CAST(field AS DATE) 而不是强制转换运算符 ::date 以避免 Hibernate/JPA 出现问题。

标签: postgresql


【解决方案1】:

你可以通过这种方式得到它,格式化最终结果。

select to_char(min(daterange), 'MM/DD/YYYY') as min_cf, 
       to_char(max(daterange), 'MM/DD/YYYY') as max_cf
from   (select to_date(table1.daterange, 'DD/MM/YYYY') as daterange 
        from table1
        inner join table2 
        on table1.sid = table2.sid) tt;
min_cf | max_cf :--------- | :--------- 2013 年 12 月 7 日 | 2019 年 1 月 7 日

dbfiddle here

【讨论】:

  • 很高兴为您提供帮助
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-07-31
  • 1970-01-01
  • 2013-10-05
相关资源
最近更新 更多