【问题标题】:Change formatting of date upon calling value根据调用值更改日期格式
【发布时间】:2020-12-23 19:53:05
【问题描述】:

在我的前端,我使用 Angular (11) Material Datepicker 元素让用户选择一个日期。对此的格式化是使用 MAT_DATE_LOCALE 提供程序完成的,它是 dd-MM-YYYY,所以今天是 23-12-2020。此 Datepicker 使用响应式表单链接到 FormControl

虽然我对向用户表示日期的方式感到满意,但我想以YYYY-MM-dd 格式发送日期。似乎 Datepicker 正在将 FormControl 的值设置为 Date 对象,我不知道是否可以更改它。我当然可以创建一个方法来更改我需要在 POST 之前更改的所有字段,但这似乎很笨拙,我觉得可以更优雅地完成。

【问题讨论】:

  • Material Datepicker 由 javascript 的 Date 对象按缺陷提供,只需在您的服务中将方法接收的 Date 变量转换为字符串,然后再制作 httpClient.post
  • @Eliseo 这实际上已经发生了;我以 JSON 格式获取它们并用结果填充我的 FormControl。如果我在不修改它们的情况下发布,它们的类型是string。只有当我使用 Datepicker 更改它时,它才会更改为 Date 对象。
  • 我尝试在答案中解释这个想法

标签: angular angular-material angular-forms form-control


【解决方案1】:

露西娅,想象一下我们收到了一些喜欢

{
  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})
}

【讨论】:

  • 我明白你现在的意思了,这确实有道理。谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-11-04
  • 1970-01-01
  • 1970-01-01
  • 2016-06-15
相关资源
最近更新 更多