1. Date-time format settings in Freemarker
Freemarker can format date, time, and datetime three types of datetime, respectively, for example:
config.setDateTimeFormat("yyyy-MM-dd HH:mm:ss"); config.setDateFormat("yyyy-MM-dd");
When we use a page variable, ?date
?time
?datetime
It will be displayed in the corresponding format of the above settings, respectively.
2. Under what circumstances can not be used
?date
?time
?datetime
Freemarker will java.sql.Date
java.sql.Time
java.sql.Timestamp
automatically recognize variables of the type as date
time
datetime
. So when the variable is the above three types, Freemarker automatically matches the format of the setting, and does not need to be appended to the variable ?date
?time
?datetime
.
3. The variable is
java.util.Date
Type of confusion
Freemarker cannot automatically identify java.util.Date
which format the type should display, and you need to explicitly specify the format it is to display, otherwise Freemarker will throw an exception. But there are times when we find that a java.util.Date
variable of type does not have a specified format that can be displayed correctly on the page, what is the case? For example:
@Entity@Table(name = "Tmp_Company")public class Company extends UuidEntity { ... /** 成立日期 */ @Temporal(TemporalType.DATE) private java.util.Date foundDate; ...}
When the view page is used ${company.foundDate}
, the format is not specified but is displayed correctly. This is because @Temporal(TemporalType.DATE)
annotations allow the ORM framework to automatically convert the type to a type when the data is fetched from the database java.util.Date
java.sql.Date
, and Freemarker automatically recognizes its format. If you add annotations to this business entity class, @Cache
using different caching strategies, there will be more interesting phenomena, and this will not unfold.
4. Conclusion
When the variable type is, it is java.sql.Date
java.sql.Time
java.sql.Timestamp
not necessary to specify the format, and when the variable type is, specifying the format is the surest java.util.Date
way.
5. Supplement
If the founddate in the example above is allowed to be null, how will the page be written without error?
${foundDate?date!} ${(foundDate?date)!} ${foundDate!?date}
It is a very ugly way of writing, but the above is wrong, the correct only to write:
Date-time processing in Freemarker