Spring boot/thymeleaf时间问题整理

  1. 前台时间转后台
public class DateEditor extends PropertyEditorSupport {


    public static final DateFormat DATEFORMAT = new SimpleDateFormat("yyyy-MM-dd");
    public static final DateFormat TIMEFORMAT = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    public static final DateFormat ONLY_TIMEFORMAT = new SimpleDateFormat("HH:mm:ss");

    private DateFormat dateFormat;
    private boolean allowEmpty = true;


    /**
     * Parse the Date from the given text, using the specified DateFormat.
     */
    @Override
    public void setAsText(String text) throws IllegalArgumentException {
        if (text == null || "".equals(text)) {
            setValue(null);
        } else {
            try {
                boolean time = text.contains(":");
                boolean date = text.contains("-");

                if(date && time){
                    setValue(TIMEFORMAT.parse(text));
                }
                if(date && !time){
                    setValue(DATEFORMAT.parse(text));
                }
                if(!date && time){
                    setValue(ONLY_TIMEFORMAT.parse(text));
                }
            } catch (ParseException ex) {
                throw new IllegalArgumentException("Could not parse date: " + ex.getMessage(), ex);
            }
        }
    }

    /**
     * Format the Date as String, using the specified DateFormat.
     */
    @Override
    public String getAsText() {
        Date value = (Date) getValue();
        DateFormat dateFormat = this.dateFormat;
        if(dateFormat == null)
            dateFormat = TIMEFORMAT;
        return (value != null ? dateFormat.format(value) : "");
    }

}
  1. controller中的需要增加以下,如果有baseController时,可以写到baseController中,这样就不用每个类中都写了
    @InitBinder
    public void initBinder(WebDataBinder binder) {
        // 对于需要转换为Date类型的属性,使用DateEditor进行处理
        binder.registerCustomEditor(Date.class, new DateEditor());
    }
  1. 后端向前端返回时,需要对日期进行格式批如下:
<td th:text="${#dates.format(fleeceRecord.cashmereDate,'yyyy-MM-dd')}"></td>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值