I have an object who has a property 'birthDate' of type Date.
On screen, I should display the birthday in format DD/MM/YYYY. Now I use bootstrap bsDatePicker.
But in the database, it is stored in the format YYYY-MM-DD(type string). So to submit the modification, I should convert the birthday to this format.
Can you tell me how to serialize the Date(DD/MM/YYYY) to the format YYYY-MM-DD in the JSON request?
Do you have any good idea to optimize the conversion without any change in the database?
Thank you
First you are going to create a function that accepts a string that contains the date. Then convert it. At the end of the function I have some ternary code because if you don't add that part, the date could be 2018-4-2 and you want it 2018-04-02
dateFormater(date:string):string{
const today = new Date(date);
const day = today.getDate()+1;
const month = today.getMonth()+1;
const year = today.getFullYear();
return year + "-" + (month<10 ? ("0" + month) : month)+ "-" + (day<10 ? ("0" + day) : day);
}
If its a string, you could just extract the relevant data and returning the correct format, needed to be submit in your json. A possible helper function:
formatDate():string{
const today = new Date();
const day = today.getDate();
const month = today.getMonth()+1; // this will return 0-11 so you will need to add 1 to make it, 1-12
const year = today.getFullYear();
return year+"-"+month+"-"+day;
}
this will return "2018-10-19"
.
Thank you for all your anwser, this is what i did:
I map the origin object to the request type with reflxion, for the date:
if(item[key] instanceof Date) {
value = this.dataPipe.transform(item[key], 'yyyy-MM-dd').toString();
}else {
value = item[key].toString();
}