Tengo esta entidad simple administrada por spring. Me gustaría trabajar con los campos endDate y startDate que los recibo en formato JSON en JavaScript
JSON recibido
{ "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" }entidad 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; }Modelo de Cupón en 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 = ""; } // 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);Puedes hacer esto
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')) // DMYYYY console.log(jsObjStartDate.toLocaleDateString('pt-PT')) // DD/MM/YYYY