How to format to JavaScript Date received in JSON?


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;

@Table(name = "coupon")
public class Coupon {

    // FIELDS
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private int id;  

    @JsonIdentityReference(alwaysAsId = true)
    private Company company; 

    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 = "";


You can do like this

const startDate="2021-06-30";
const jsObjStartDate = new Date(startDate);
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


Answered By – DevLoverUmar

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published