600字范文,内容丰富有趣,生活中的好帮手!
600字范文 > angular 字符串转换成数字_Angular日期在TypeScript中格式化转换应用

angular 字符串转换成数字_Angular日期在TypeScript中格式化转换应用

时间:2024-06-03 16:17:51

相关推荐

angular 字符串转换成数字_Angular日期在TypeScript中格式化转换应用

组件模板中我们常常使用Angular内置管道DatePipe将其日期格式化,如同{{ startTime | date:'yyyy-MM-dd' }}这般操作,即可转换为字符串格式。那么在TS文件中我们也可以通过DatePipe或formatDate方法将其格式化。
Angular日期在TypeScript中格式化转换应用​

在前端项目开发过程中往往会遇将日期格式化,转换为友好显示格式,如同将"Sat Jun 01 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:日期时间格式,使用预定义选项或自定义格式字符串(如:07月25日...);

locale:区域代码;

timezone:(选填) 时区;

就到这里,上次在项目框架升级到Angular8.x版本时原DatePipe方法格式化地方报错,索性将其全更换为formatDate方法。

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。