Search code examples
javascriptangulardateangular-ngmodelngx-bootstrap

Output YYYY-MM-DD not full date string


I want to update a date linked by ngModel, using ngx-bootstrap datepicker, then send it in a PUT request to my Django backend. But the date format keeps getting changed from YYYY-MM-DD (2019-08-13) to the full javascript datestring (2019-08-13T23:00:00.000Z) which wont let me send the PUT request then.

I have tried nearly everything I can find on all other problems and it just doesnt work, nothing will let me select it as YYYY-MM-DD and keep it that way in the PUT request. Any help greatly appreciated.

<input class="form-control" 
#dp="bsDatepicker" 
bsDatepicker
[(ngModel)]="project.Start_Date2"
name="Start_Date2" 
[bsConfig]="{
    dateInputFormat: 'YYYY-MM-DD',
    isAnimated: true, 
    containerClass: 'theme-default' 
}">

I just want to be able to send my PUT request with the date format as YYYY-MM-DD. I am not sure if ngx-bootstrap will do it because when I pick a date with it, it converts it to the long string which then doesn't work in the PUT request.


Solution

  • The reason the date format keeps getting reverted is precisely because you use the ngModel, ie. two-way binding. The ngx-datepicker keeps pushing the selected value to your bound variable (Start_Date2). That is alright and expected.

    I don't know how you do your PUT request, but you're going to need to do your format conversion either on the fly inside the request function or introduce another variable which will hold your date with the desired format.

    I assume you use the angular HttpClient and the put request looks something like

    this.http.put('https://example.com/dates/1', project.Start_Date2)
    

    So what you can do is create a conversion function and convert the format inside the put call.

    
    function myDateFormatFunction(inputDate) {
      let d = new Date(inputDate) // this might not be needed if the date is already a Date() object
      // YYYY-MM-DD
      return d.getFullYear() + '-' + ('0' + (d.getMonth()+1)).slice(-2) + '-' + ('0' + d.getDate()).slice(-2); // the zeroes and slice weirdness is to have nice padding, borrowed from https://stackoverflow.com/a/3605248/3158815
    }
    
    this.http.put('https://example.com/dates/1', myDateFormatFunction(project.Start_Date2))