如何在将数据发布到 REST 端点时在 AngularJS 中格式化日期

How to format date in AngularJS when posting data to a REST end point

本文关键字:端点 AngularJS 格式化 日期 REST 数据      更新时间:2023-09-26

我有一个Spring MVC REST后端应用程序。我正在以"mm/dd/yyyy"格式将日期发送给客户端。

但是,如果我将日期格式化为"mm/dd/yyyy"并将其回发,则数据绑定将失败。

这是我的 Spring customdateserializer obj,它在将日期发送到前端时将 java.util.date 转换为 mm/dd/yyy

public class CustomDateSerializer extends JsonSerializer<Date> {  
    @Override
    public void serialize(Date value, JsonGenerator gen, SerializerProvider arg2) throws 
        IOException, JsonProcessingException {      
        SimpleDateFormat formatter = new SimpleDateFormat("MM/dd/yyyy");
        String formattedDate = formatter.format(value);
        gen.writeString(formattedDate);
    }
}

下面是数据绑定失败的对象

@Entity
@Table(name = "bill")
public class Bill implements GenericObject {
    @Temporal(javax.persistence.TemporalType.TIMESTAMP)
    private Date billDate;
    @JsonSerialize(using = CustomDateSerializer.class)
    public Date getBillDate() {
        return billDate;
    }
    public void setBillDate(Date billDate) {
        this.billDate = billDate;
    }
}

这是我发布数据的终点(Spring MVC 控制器)

@RequestMapping(value = { "/user/{userId}/bill" }, method = { RequestMethod.POST })
    public void addBill(@RequestBody Bill bill_p,@PathVariable("userId") int userId,
            HttpServletResponse httpResponse_p, WebRequest request_p) {
        processing......
    }

我能说的是不要将格式化的日期发送到浏览器。发送Date类型结构''对象,让日期格式在客户端处理。Angular 有一个用于此任务的date过滤器。

同样,将数据发送到服务器,不要发送任何格式化的数据,而是模型日期值,我相信服务器端反序列化程序会处理它。查看在网络上发送的格式,以满足您的请求。