如何在JSON格式java.sql.date JavaScript日期收到了吗?



我有这个简单的实体管理的春天。我想使用endDatestartDate字段,我在JavaScript中以JSON格式接收它们

收到的JSON -

{
"id": 151,
"company": {
"id": 1,
"name": "companyName5"
},
"category": "Automotive",
"title": "Automotive",
"description": "Automotive",
"startDate": "2021-06-30",
"endDate": "2022-09-30",
"amount": 50,
"price": 50,
"image": "imgPath"
}

Java实体-

import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.annotation.JsonIdentityReference;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import lombok.*;
import javax.persistence.*;
import java.sql.Date;
@Entity
@AllArgsConstructor
@NoArgsConstructor
@Builder
@Data
@Table(name = "coupon")
public class Coupon {
// FIELDS
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;  
@ManyToOne()
@ToString.Exclude
@JsonIdentityReference(alwaysAsId = true)
@JsonIgnoreProperties({"email","password","coupons"})
private Company company; 
@Enumerated(EnumType.STRING)
private Category category; 
private String title;
private String description; 
private Date startDate; 
private Date endDate; 
private int amount; 
private double price; 
private String image; 
}

JavaScript中的优惠券模型(TypeScript)

class Coupon {
public id: number = 0; 
public comapnyId:number = 0;
public category:string = "";
public title:string = "";
public description: string = "";
public startDate: string;
public endDate: string;
public amount:number = 0;
public price:number = 0;
public image:string = "";
}

你可以这样做

const startDate="2021-06-30";
const jsObjStartDate = new Date(startDate);
console.log(jsObjStartDate);
console.log(jsObjStartDate.toISOString().slice(0, 10)) // YYYY-MM-DD
console.log(jsObjStartDate.toLocaleDateString('en-US')) // M/D/YYYY
console.log(jsObjStartDate.toLocaleDateString('de-DE')) // D.M.YYYY
console.log(jsObjStartDate.toLocaleDateString('pt-PT')) // DD/MM/YYYY

参考

// parse JSON to JS object, get startDate and endDate fields via object destructuring   
const {startDate, endDATE} = JSON.parse(`{
"id": 151,
"company": {
"id": 1,
"name": "companyName5"
},
"category": "Automotive",
"title": "Automotive",
"description": "Automotive",
"startDate": "2021-06-30",
"endDate": "2022-09-30",
"amount": 50,
"price": 50,
"image": "imgPath"
}`);

// instantiate Date js objects with startDate and endDate provided to Date constructor
const jsObjStartDate = new Date(startDate);
const jsObjEndDate = new Date(endDate);