如何在Angular 4中格式化日期?调整客户端视图日期显示格式
解决Angular 4中月份日期的视图格式转换问题
嘿,这个需求我之前做项目的时候刚好碰到过!因为type="month"的输入框默认只能识别和返回yyyy-mm格式,但要在视图里改成mm-yyyy或者January 2018这种友好格式,其实用Angular的管道或者双向绑定的 getter/setter 就能搞定,分两种场景给你详细说:
一、纯显示场景(非输入框)
如果只是把保存的yyyy-mm字符串在页面上展示成目标格式,最简单的方式是用自定义管道或者改造原生的DatePipe:
方法1:自定义月份格式管道
这种方式最灵活,专门处理yyyy-mm字符串的转换,不用每次转成Date对象。
- 先创建一个管道文件
month-format.pipe.ts:
import { Pipe, PipeTransform } from '@angular/core'; @Pipe({ name: 'monthFormat' }) export class MonthFormatPipe implements PipeTransform { // 支持两种格式:默认mm-yyyy,传'full'则显示January 2018 transform(value: string, formatType: string = 'mm-yyyy'): string { // 校验输入格式是否合法 if (!value || value.length !== 7 || !value.includes('-')) return value; const [year, month] = value.split('-'); const monthNames = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]; switch (formatType) { case 'full': return `${monthNames[parseInt(month) - 1]} ${year}`; case 'mm-yyyy': default: return `${month}-${year}`; } } }
- 在你的模块里声明这个管道:
import { NgModule } from '@angular/core'; import { MonthFormatPipe } from './month-format.pipe'; @NgModule({ declarations: [MonthFormatPipe], exports: [MonthFormatPipe] // 如果要在其他组件用,记得导出 }) export class SharedModule {}
- 模板里直接使用:
<!-- 显示成 mm-yyyy --> <p>当前选择月份:{{ savedMonth | monthFormat }}</p> <!-- 显示成 January 2018 --> <p>当前选择月份:{{ savedMonth | monthFormat:'full' }}</p>
这里的savedMonth就是你保存的yyyy-mm格式字符串。
方法2:用原生DatePipe转换
原生DatePipe需要Date类型,所以得先把yyyy-mm转成Date对象:
<!-- 显示成 mm-yyyy --> <p>{{ getMonthDate(savedMonth) | date:'MM-yyyy' }}</p> <!-- 显示成 January 2018 --> <p>{{ getMonthDate(savedMonth) | date:'MMMM yyyy' }}</p>
然后在组件里写转换方法:
getMonthDate(monthStr: string): Date { // 给字符串加个日期,转成合法的Date对象 return new Date(`${monthStr}-01`); }
二、输入框内显示自定义格式
如果要让用户在输入框里看到的是mm-yyyy或者January 2018,但保存的还是yyyy-mm,因为原生type="month"输入框不支持自定义显示格式,所以有两种方案:
方案1:用ngModel的getter/setter做双向绑定转换
通过组件里的属性拦截,把显示和存储的格式分开:
组件代码:
import { Component } from '@angular/core'; @Component({ selector: 'app-month-picker', templateUrl: './month-picker.component.html' }) export class MonthPickerComponent { // 内部存储yyyy-mm格式的值 private _selectedMonth: string; // 对外暴露的显示用属性,返回mm-yyyy格式 get displayMonth(): string { if (!this._selectedMonth) return ''; const [year, month] = this._selectedMonth.split('-'); return `${month}-${year}`; } // 接收输入框的值,转成yyyy-mm格式存储 set displayMonth(value: string) { if (!value || value.length !== 7 || !value.includes('-')) return; const [month, year] = value.split('-'); // 这里可以加校验,确保month是01-12,year是合法年份 this._selectedMonth = `${year}-${month}`; } // 保存方法,直接用this._selectedMonth即可 saveMonth() { console.log('保存的格式:', this._selectedMonth); // 输出yyyy-mm } }
模板代码:
<input type="text" class="form-control" [(ngModel)]="displayMonth" placeholder="请输入mm-yyyy"> <button class="btn btn-primary mt-2" (click)="saveMonth()">保存</button>
方案2:用第三方日期组件(推荐)
如果想要更友好的选择器(比如下拉选月份年份),可以用ngx-bootstrap的Datepicker(因为你用了Bootstrap,适配性很好),支持自定义显示格式和只选年月:
- 先安装依赖(Angular 4对应ngx-bootstrap的2.x版本):
npm install ngx-bootstrap@2.0.0 --save
- 在模块里引入Datepicker模块:
import { BsDatepickerModule } from 'ngx-bootstrap/datepicker'; @NgModule({ imports: [BsDatepickerModule.forRoot()] }) export class AppModule {}
- 模板里使用:
<input type="text" class="form-control" bsDatepicker [(bsValue)]="selectedDate" [bsConfig]="{ dateInputFormat: 'MMMM yyyy', // 显示格式:January 2018 minMode: 'month', // 只允许选择月份 containerClass: 'theme-blue' // 适配Bootstrap主题 }"> <button class="btn btn-primary mt-2" (click)="saveMonth()">保存</button>
- 组件里转成
yyyy-mm格式保存:
import { Component } from '@angular/core'; @Component({ selector: 'app-month-picker', templateUrl: './month-picker.component.html' }) export class MonthPickerComponent { selectedDate: Date; saveMonth() { if (!this.selectedDate) return; const year = this.selectedDate.getFullYear(); const month = ('0' + (this.selectedDate.getMonth() + 1)).slice(-2); const savedMonth = `${year}-${month}`; console.log('保存的格式:', savedMonth); // 输出yyyy-mm } }
这样用户看到的是友好的格式,保存的还是你需要的yyyy-mm,完美适配你的需求!
内容的提问来源于stack exchange,提问作者Kenzo
相关产品推荐
相关产品推荐

