angular 字符串转换成数字_Angular日期在TypeScript中格式化转换应用
在前端項目開發過程中往往會遇將日期格式化,轉換為友好顯示格式,如同將"Sat Jun 01 2019 23:21:55 GMT 0800"格式化為"yyyy-MM-dd"(年-月-日);Angular項目中我們常常使用其內置管道將其格式轉換e.g. {{ startTime | date:"yyyy-MM-dd" }},以達到所要顯示的格式;下面我們看看在TypeScript(.ts)中的方法應用。
Angular6.x之前一直使用DatePipe轉換日期格式,在angular6.x 之后API中又發現formatDate方法,具體就不曉得了,我一直使用DatePipe。
DatePipe在.TS的應用
import { DatePipe } from '@angular/common';export class DemoComponent implements OnInit { constructor(private datePipe: DatePipe) {}formatDateFun(date) {return this.datePipe.transform(date, 'yyyy-MM-dd');} }別忘記在當前模塊中將其providers: [DatePipe]添加。
formatDate在.TS的應用
import { Component, OnInit, Inject, LOCALE_ID } from '@angular/core'; import { formatDate } from '@angular/common';export class DemoComponent implements OnInit {constructor(@Inject(LOCALE_ID) private locale: string) {}formatDateFun(date) {return formatDate(date, 'yyyy-MM-dd', this.locale);} }如上設置記得在項目根模塊配置
import { NgModule, LOCALE_ID } from '@angular/core'; providers:[{provide: LOCALE_ID, useValue: 'zh-Hans' }]又或者不設置,則在formatDate中直接使用'zh-Hans'(簡體中文)即可,如:
formatDate(new Date(), 'yyyy-MM-dd', 'zh-Hans')其語法結構如:
formatDate(value: string | number | Date, format: string, locale: string, timezone?)value: 要格式化的日期,是一個日期、數字(從 UTC 時代以來的毫秒數)或 ISO 字符串;
format: 日期時間格式,使用預定義選項或自定義格式字符串(如:2019年07月25日...);
locale: 區域代碼;
timezone: (選填) 時區;
就到這里,上次在項目框架升級到Angular8.x版本時原 DatePipe 方法格式化地方報錯,索性將其全更換為 formatDate 方法。
總結
以上是生活随笔為你收集整理的angular 字符串转换成数字_Angular日期在TypeScript中格式化转换应用的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 去调频体制下的 rd算法_【技术文章】一
- 下一篇: 苹果切换输入法_日语输入法哪个好