Reputation: 21
When I use MS SQL database, I do this to convert date in timestamp to "YYYY-mm-dd" format.
CONVERT(DATE, "Timestamp")
I need to do the same function using HQL.
Which function will remove all the time indices and give the date in "YYYY-mm-dd" format?
Upvotes: 2
Views: 27460
Reputation: 31
Use this hive function:
date_format(mydatewithtimestamp,'dd-MM-yyyy')
Reference: https://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html
Upvotes: 3
Reputation: 462
You can use the following that converts a date to a string with the specified format:
to_char(mydate,'yyyy-mm-dd')
Upvotes: 5
Reputation: 1619
You have to either use vendor-specific functions or extend the dialect. Unfortunately this isn't supported out of the box in Hibernate (not sure why as would have thought it was simple to implement).
Extending the dialect is simple and is a better option as it keeps your application database-agnostic and works seamlessly across the app.
Create classes for the dialects that you want to extend such as:
class ExtendedOracle10gDialect extends Oracle10gDialect {
ExtendedOracle10gDialect() {
// Add a generic 'date_format' function that can be used across databases
registerFunction("date_format", new SQLFunctionTemplate(StandardBasicTypes.DATE, "to_char(?1, ?2)"));
}
}
Then change your datasource to use the custom dialect, for example by changing hibernate.cfg.xml:
<property name="hibernate.dialect">com.mycompany.dialect.ExtendedOracle10gDialect</property>
You can then use DATE_FORMAT(MYDATE,'YYYY-MM-DD')
in your HQL
MySQL / MariaDB:
DATE_FORMAT(MYDATE,'YYYY-MM-DD')
SQL Server:
FORMAT(MYDATE,'YYYY-MM-DD')
Oracle / PostgreSQL:
TO_CHAR(MYDATE,'YYYY-MM-DD')
Upvotes: 3