@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

你可能感兴趣的:(Java,spring,java,spring)