Change formatting of date upon calling value

天大地大妈咪最大 提交于 2021-01-29 09:15:36

问题


On my frontend, I use an Angular (11) Material Datepicker element to let the user pick a date. The formatting for this is done using the MAT_DATE_LOCALE provider, and it is dd-MM-YYYY, so 23-12-2020 for today. This Datepicker is linked to a FormControl using reactive forms.

While I am content with how the date is represented to the user, I'd like to send the date in a YYYY-MM-dd format. It seems the Datepicker is setting the value of the FormControl to a Date object and I don't know if I can change this. I could of course create a method to change all the fields I need changed before POSTing, but this seems clumpy and I feel like it could be done more elegantly.


回答1:


Luctia, imagine we received some like

{
  name:'Name'
  birthdate:'1980-10-21'
}

You can has a service like

getData()
{
    return this.httpClient(...).pipe(map(x=>{
        x.birthdate=new Date(x.birthdate)
        return x
    })
}
//See that subscribing to the service in birthdate we has an object Date

getList(){
    return this.httpClient(...).pipe(map((list:any[])=>{
        list.forEach(x=>{
           x.birthdate=new Date(x.birthdate)
        })
        return list
    })
}
//see that when subcribing to List, return an array of object with birthdate is Date

updateData(data)
{
    //we calculate a birthdate string
    const birthdate=data.getFullYear()+'-'+
                   ('00'+(data.getMonth()+1).slice(-2)+'-'+
                   ('00'+data.getDate()).slice(-2)

    //send to post the data but the birthDate a string
    return this.httpClient.post(...,{...data,birthdate:birthdate})
}


来源:https://stackoverflow.com/questions/65430165/change-formatting-of-date-upon-calling-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!