@InitBinder应用,使用LocalDateTime接收时间戳

@InitBinder应用,使用LocalDateTime接收时间戳

前端转时间戳(格式:1668759573),后端使用 LocalDateTime 类进行接收

1、自定义转换器

package com.xjhqre.test.config;

import java.beans.PropertyEditorSupport;
import java.time.LocalDateTime;
import java.time.OffsetDateTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;

import org.apache.commons.lang3.math.NumberUtils;

public class CustomLocalDateTimeConverter extends PropertyEditorSupport {
    private static final String PATTERN = "yyyy-MM-dd HH:mm:ss";
    private static final ZoneOffset ZONE_OFFSET;

    static {
        OffsetDateTime odt = OffsetDateTime.now(ZoneId.systemDefault());
        ZONE_OFFSET = odt.getOffset();
    }

    @Override
    public void setAsText(String text) throws IllegalArgumentException {
        // 如果传进来的参数是数字且为 13 位,匹配我们传进来的时间戳
        if (NumberUtils.isDigits(text) && text.length() == 13) {
            this.setValue(LocalDateTime.ofEpochSecond(NumberUtils.toLong(text) / 1000L, 0, ZONE_OFFSET));
        } else if (NumberUtils.isDigits(text) && text.length() == 10) {
            this.setValue(LocalDateTime.ofEpochSecond(NumberUtils.toLong(text), 0, ZONE_OFFSET));
        } else {
            try {
                this.setValue(LocalDateTime.parse(text, DateTimeFormatter.ofPattern(PATTERN)));
            } catch (Exception var2) {
                this.setValue(null);
            }
        }
    }
}

2、编写Controller

package com.xjhqre.test.controller;

import java.time.LocalDateTime;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.xjhqre.test.R;
import com.xjhqre.test.config.CustomLocalDateTimeConverter;
import com.xjhqre.test.dto.Person;
import com.xjhqre.test.service.TestService;

@RestController
@RequestMapping("/com/xjhqre")
public class TestController {


    /**
     * 注册自定义的转换器,只在当前TestController生效
     * 
     * @param binder
     */
    @InitBinder
    public void initBinder(WebDataBinder binder) {
        binder.registerCustomEditor(LocalDateTime.class, new CustomLocalDateTimeConverter());
    }

    @GetMapping("/test")
    public R test(LocalDateTime time) {
        System.out.println(time);
        return R.ok();
    }

}

3、测试

发送Get请求:http://127.0.0.1:8080/com/xjhqre/test2?time=1668742425

结果:

2022-11-18T11:33:45
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值