【问题标题】:How to change the output date format of input type="date" in angular 4?如何更改角度4中输入类型=“日期”的输出日期格式?
【发布时间】:2018-10-30 21:42:39
【问题描述】:

实际上我正在使用 Angular 4 应用程序。我遇到这样的情况,我必须将日期作为 dd/mm/yyyy 发送到服务器。

我使用属性作为输入类型="日期"。但此属性返回的值类似于 yyyy/mm/dd。那么如何更改日期的输出格式。

Students.html

<input type="date" [(ngModel)]="Students.dob" name="Students.dob">

选择日期后,当我使用 console.log() 检查时。

Students.components.ts

checkDate() { console.log(Students.dob); }

最后的输出是yyyy/mm/dd.

有什么办法可以解决这个问题吗?请告诉我。

【问题讨论】:

    标签: angular angular4-forms


    【解决方案1】:

    你可以使用 DatePipe 方法。

    <input type="date" [(ngModel)]="Students.dob|date:'dd/MM/yyyy'" name="Students.dob">
    

    您可以从这里阅读更多内容。 https://angular.io/api/common/DatePipe

    【讨论】:

    • 当我在 ngModel 中使用 Pipe 表达式时显示错误,例如“在 [students.doj | date:'dd/MM/yyyy'=$event 的第 16 列的操作表达式中不能有管道] 在"
    • @VigneshMohanraj 如果你像[ngModel]="Students.dob|date 这样单向绑定模型,你可以使用这个。
    • 但问题指定了2路数据绑定
    • 你应该使用[ngModel] = "Students.dob|date" (onModelChange)="Students.dob=$event"
    【解决方案2】:

    你可以试试这个-

    import { DatePipe } from '@angular/common';
    
    checkDate() {
        let formatedDate = new DatePipe().transform(this.Students.dob, 'dd/mm/yyyy')
        console.log(formatedDate); 
      }
    

    【讨论】:

    • 有什么解决方案可以使用这种方法
    【解决方案3】:

    您可以在checkDate() 函数中使用DatePipe 将日期更改为dd/mm/yyyy 格式。如下所示。并将该日期发送到服务器端。

    首先将 DatePipe 导入到您的组件中

    import { DatePipe } from '@angular/common';
    

    然后像下面这样使用它

      checkDate() {
        const dateSendingToServer = new DatePipe('en-US').transform(this.Students.dob, 'dd/MM/yyyy')
        console.log(dateSendingToServer);
      }
    

    您可以在 STACKBLITZ DEMO 上找到工作示例。

    希望对你有所帮助!

    【讨论】:

      【解决方案4】:

      您可以使用 moment.js。另外,您需要安装并导入它。

      npm install moment --save
      
      import * as moment from 'moment'; //in your component
      

      然后使用

      checkdate(){
         const date = moment(Students.dob).format(DD-MM-YYYY);
         console.log(date);
      }
      

      【讨论】:

        猜你喜欢
        • 2019-02-23
        • 2020-09-07
        • 1970-01-01
        • 1970-01-01
        • 2018-09-29
        • 2022-01-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多