在调用值时更改日期格式
Change formatting of date upon calling value
在我的前端,我使用 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 使用反应形式。
虽然我对向用户显示日期的方式很满意,但我想以 YYYY-MM-dd
格式发送日期。似乎 Datepicker 正在将 FormControl 的值设置为 Date 对象,我不知道是否可以更改它。我当然可以创建一个方法来更改我需要在发布之前更改的所有字段,但这看起来很笨拙,我觉得它可以做得更优雅。
Luctia,想象一下我们收到了一些像
{
name:'Name'
birthdate:'1980-10-21'
}
你可以有这样的服务
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})
}
在我的前端,我使用 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 使用反应形式。
虽然我对向用户显示日期的方式很满意,但我想以 YYYY-MM-dd
格式发送日期。似乎 Datepicker 正在将 FormControl 的值设置为 Date 对象,我不知道是否可以更改它。我当然可以创建一个方法来更改我需要在发布之前更改的所有字段,但这看起来很笨拙,我觉得它可以做得更优雅。
Luctia,想象一下我们收到了一些像
{
name:'Name'
birthdate:'1980-10-21'
}
你可以有这样的服务
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})
}