1

I have created a .html and .ts file (code as below), I have used primeng component to set the calendar and the values I'm getting the data from the calendar is {Sat Mar 16 2021 10:58:55 GMT+0530 (India Standard Time)} but I need to pass the datetime values in database via formbuilder.

Question: How do I pass/send calendar date and time values to database to StartDate?

I have also used the datepipe to transform the given data to desired date and time format.

.html file

<div class="col-md-6">
     <label class="form-label">Start Date</label>
         <div class="form-control-wrap">
            <p-calendar [(ngModel)]="date_val" formControlName="StartDate" name="StartDate"                                 [showTime]="true" hourFormat="24" inputId="time" dateFormat="yy-mm-dd"></p-calendar>
         </div>
</div>

I'm getting

import { DatePipe } from '@angular/common';
export class CreateEventComponent implements OnInit {
  date_val!: Date;

  constructor(private formBuilder: FormBuilder,
    private auth: AuthService,
    private route: Router) { 
      this.form = this.formBuilder.group({
      });
   }


  ngOnInit(): void {
    var start_date =this.datepipe.transform(this.date_val, 'yyyy-MM-dd');
    this.currentUser = JSON.parse(localStorage.getItem('current_user') || '{}');

    this.createEventForm = this.formBuilder.group({
      EventName: [''],
      EventType: [''],
      HostUserEmail: this.currentUser.email,
      StartDate: this.start_date,
    });
  }
Rahul
  • 11
  • 6

1 Answers1

0

You're kinda getting confused with template based forms and reactive based forms since you are using both [(ngModel)] and formControlName for the same field. You can only use one or another.

First amend your field like so:

<p-calendar formControlName="StartDate" name="StartDate" [showTime]="true" hourFormat="24" inputId="time" dateFormat="yy-mm-dd"></p-calendar>

You are also attempting to format the date before it goes into the calendar library, however you need to keep it as a date object. I would do the following (assuming you want today's date):

ngOnInit(): void {
    
    this.currentUser = JSON.parse(localStorage.getItem('current_user') || '{}');

    this.createEventForm = this.formBuilder.group({
      EventName: [''],
      EventType: [''],
      HostUserEmail: this.currentUser.email,
      StartDate: [new Date],
    });
  }

You do however need to format the date when you send it off to an api. The format can vary wildly depending on what the api is expecting. If your api is expecting a yyyy-MM-dd format then I would try in your save method:

 save(model)
    {
let wholeObject = model.value;
wholeObject.StartDate = this.datepipe.transform(wholeObject.StartDate, 'yyyy-MM-dd');
    }
Andrew Howard
  • 2,818
  • 5
  • 33
  • 59