spring-boot - 如何在 thymeleaf 中为输入和人类可读的文本输出使用不同的日期/时间格式
问题描述
我正在使用 Spring Boot 和 Thymeleaf。
对于 html 表单日期输入字段,我必须使用 2019-10-27 日期格式。对于人类可读的文本,我更喜欢使用适合区域设置的文本,例如 27.10.2019 或 10/27/2019。
Spring Boot 和 Thymeleaf 可以很容易地指定@DateTimeFormat
和自动提取它th:field
等等。在这里,我指定了技术格式,否则我的表单既不会呈现也不会正确提交。
有没有办法让 Thymeleaf 或 Spring 在其他场合使用不同的格式?我知道我可以做到 ${#temporals.format(period.end, #messages.msg('formats.readable.date.month'))}
,但是有没有办法以某种方式注册该东西并使其可用于自动转换?
解决方案
您还可以使用一个WebDataBinder
@InitBinder
public void initBinder(WebDataBinder binder, final Locale locale) {
String dateFormat = "MM/dd/yyyy";
if(locale.getLanguage.equals("ar")){
dateFormat = "dd-MM-yyyy";
}
SimpleDateFormat sdf = new SimpleDateFormat(dateFormat);
sdf.setLenient(false);
binder.registerCustomEditor(Date.class, new CustomDateEditor(sdf, true));
}
推荐阅读
- arrays - RIDE(APL)中的多线输入?
- ios - Payfort 在最新的 ios 版本 13.3.1 中无法在实时服务中使用
- r - 用负比例拟合 log pearson III 的问题
- javascript - requestAnimationFrame 似乎无效
- javascript - 按月份和日期的总值对数组进行排序 - Angular
- python - sort list alphabetically by field in python
- react-native - FlatList 底部的 TextInput 元素存在问题
- python - 如何使用从 API 传递的多个过滤器的 lambda 函数查询 dynamoDB
- amazon-web-services - ECS Fargate 新版任务定义
- sapui5 - SAPUI5中如何给Token添加操作?