Java hql 中的日期格式
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20122949/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Date format in hql
提问by Montroz
I have hql like
我有 hql 喜欢
hql="SELECT DISTINCT C FROM Client C
WHERE lower(str(C.name)) like '%"+sSearch
+ "%' OR str(day(C.birthday)) like '%"+sSearch "%';
As you can see, i can search sSearch in my table.
如您所见,我可以在我的表中搜索 sSearch。
But problem is that sSearch can have dd.MM.yyyy format or can not be a date (e.g. sSearch="John"), and DATE type has yyyy-MM-dd format in DB.
但问题是 sSearch 可以有 dd.MM.yyyy 格式或不能是日期(例如 sSearch="John"),并且 DATE 类型在 DB 中有 yyyy-MM-dd 格式。
I want to select date in needed format dd.MM.yyyy as string for using expression 'like'.
我想以需要的格式 dd.MM.yyyy 选择日期作为使用表达式“like”的字符串。
Thanks.
谢谢。
Solved this problem with
解决了这个问题
hql="SELECT DISTINCT C FROM Client C
WHERE lower(str(C.name)) like '%"+sSearch
+ "%' OR concat(str(day(C.birthday)),'.',str(month(C.birthday)),'.',
str(year(C.birthday))) like '%"+sSearch "%';
回答by StackBox
if you are using mysql, you can use mysql, you can use date_format .
如果您使用的是 mysql,您可以使用 mysql,您可以使用 date_format 。
"select dictinct c from Client c where lower(str(C.name)) like '%" + sSearch + "%' or
date_format(C.birthday,'%d.%m.%Y') lkie '%" + sSearch +"%'"
but I prefer to convert the sSearch to String like 'yyyy-MM-dd' on service layer or controller layer, thoughs i can use code like this.
但我更喜欢在服务层或控制器层将 sSearch 转换为字符串,如“yyyy-MM-dd”,尽管我可以使用这样的代码。
" ... C.birtyday like '%"+ sSearch + "%'"
回答by Camilo Diaz
You could use a Dateformat to format the date String.
您可以使用 Dateformat 来格式化日期字符串。
DateFormat dateFormat1 = new SimpleDateFormat("dd.MM.yyy");
DateFormat dateFormat2 = new SimpleDateFormat("yyyy-MM-dd");
Date d = dateFormat1.parse(sSearch);
hql="SELECT DISTINCT C FROM Client C
WHERE lower(str(C.name)) like '%"+sSearch
+ "%' OR str(day(C.birthday)) like '%"+ dateFormat2.format(d) +"%';