简体   繁体   English

如何在 angular 4 中更改 input type="date" 的输出日期格式?

[英]How to change the output date format of input type=“date” in angular 4?

Actually I am working with angular 4 application.实际上我正在使用 angular 4 应用程序。 I am having a scenario like, I have to send the Date for as dd/mm/yyyy to the server.我有一个场景,我必须将日期作为dd/mm/yyyy发送到服务器。

I am using property as input type ="date".我使用属性作为输入类型 =“日期”。 But this property returns the value like yyyy/mm/dd .但是此属性返回的值类似于yyyy/mm/dd so how do I change the output format of the Date.那么如何更改日期的输出格式。

Students.html学生.html

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

After selecting the date, when I am check with console.log().选择日期后,当我检查 console.log() 时。

Students.components.ts Students.components.ts

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

Finally the output was yyyy/mm/dd.最后输出是yyyy/mm/dd。 . .

Is there any way to overcome this issue?有没有办法克服这个问题? kindly let me know.请告诉我。

You could change the date into dd/mm/yyyy format using DatePipe inside the checkDate() function.您可以在checkDate()函数中使用DatePipe将日期更改为dd/mm/yyyy格式。 like below.像下面。 And send that date into the server side.并将该日期发送到服务器端。

first import the DatePipe into your component首先将DatePipe导入到您的组件中

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

then use it like below然后像下面一样使用它

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

working example you could be found here on STACKBLITZ DEMO .您可以在STACKBLITZ DEMO上找到工作示例。

Hope this will help to you!希望这对你有帮助!

You could try this -你可以试试这个——

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

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

You can use DatePipe method.您可以使用 DatePipe 方法。

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

You can read more from here.你可以从这里阅读更多。 https://angular.io/api/common/DatePipe https://angular.io/api/common/DatePipe

You can use moment.js .您可以使用moment.js Also, you need to install and import it.此外,您需要安装并导入它。

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

then use然后使用

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM