I have a question. If I have a datepicker that returns me data like this:
How can I convert this result into a date of type ISO? so that it can be stored in MongoDB.
This is the code of the html part.
<form [formGroup]="dateForm" (submit)="Date()">
<div >
<div >
<input readonly formControlName="date"
name="dp" [(ngModel)]="model" ngbDatepicker #d="ngbDatepicker">
<button (click)="d.toggle()" type="button">
Date
</button>
</div>
</form>
This is the typescript part:
ngOnInit(): void {
this.dateForm = this.fb.group({
date: ['', Validators.required]
})
}
Date(){
const { date } = this.dateForm.value
console.log(date)
}
Thanks in advance.
CodePudding user response:
According to ng-bootstrap's official docs you should configure an NgbDateAdapte
service and provide it:
The docs provide a good example on how to do it
@Injectable()
export class CustomDateParserFormatter extends NgbDateParserFormatter {
readonly DELIMITER = '/';
parse(value: string): NgbDateStruct | null {
if (value) {
const date = value.split(this.DELIMITER);
return {
day : parseInt(date[0], 10),
month : parseInt(date[1], 10),
year : parseInt(date[2], 10)
};
}
return null;
}
format(date: NgbDateStruct | null): string {
return date ? date.day this.DELIMITER date.month this.DELIMITER date.year : '';
}
}
(don't forget to provide it in your root app)
CodePudding user response:
Youn can always use toISOString
function to convert your date into ISO
format. Also try changing const
keyword into date type. Date.toISOString()
CodePudding user response:
Simply add toISOString()
to your destructured object property named date
above:
Examples as as on MDN Documentation:
const event = new Date('05 October 2011 14:48 UTC');
console.log(event.toString());
// expected output: Wed Oct 05 2011 16:48:00 GMT 0200 (CEST)
// (note: your timezone may vary)
console.log(event.toISOString());
// expected output: 2011-10-05T14:48:00.000Z