I have this simple entity managed by spring.
I would like to work with the endDate
and startDate
fields that I receive them in JSON format in JavaScript
received 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 entity -
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;
}
Coupon Model in 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 = "";
}
CodePudding user response:
// 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);
CodePudding user response:
You can do like this
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