调用值时更改日期格式 [英] Change formatting of date upon calling value

查看:28
本文介绍了调用值时更改日期格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

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

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.

推荐答案

Luctia,想象一下我们收到了一些喜欢

Luctia, imagine we received some like

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

这篇关于调用值时更改日期格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆