如何在Angular2项目中将moment.js实现为管道
How to implement moment.js as a pipe in an Angular2 project
我想在angular2项目中实现moment.js库,以便将UTC
时间转换为某个时区Europe/london
,并使用moment
和[moment timezone]
1
到目前为止,我已经使用以下命令在Angular2项目中安装了moment.js
:
npm安装时刻--保存
这是我当前的代码:
import { Component, Pipe, PipeTransform } from '@angular/core';
import * as moment from 'moment';
@Pipe({ name: 'moment' })
class MomentPipe{
transform(date, format) {
return moment(date).format(format);
}
}
Html:
我收到了来自后端的时间作为对象
//time.bookingTime.iso == 2016-07-20T21:00:00.000Z
{{time.bookingTime.iso | moment}}
它对我不起作用,我认为我有错误的实现
更新:2018年6月
关于PIPES的官方文档
要了解字体中的Moment和Moment日期格式。
下面给出的例子基于这里的问题!使用PIPE
技术,我们也可以在角视图中使用矩(日期格式)。
MomentPipe.ts
import { Pipe, PipeTransform } from '@angular/core';
import * as moment from 'moment';
@Pipe({ name: 'dateFormat' })
export class MomentPipe implements PipeTransform {
transform(value: Date | moment.Moment, dateFormat: string): any {
return moment(value).format(dateFormat);
}
}
必须在AppModule的声明数组中包含管道
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
import { MomentPipe } from './momentPipe';
@NgModule({
imports: [
// Your Modules
],
declarations: [
AppComponent,
// Your Components
MomentPipe
],
providers: [
// Your Providers
]
})
export class AppModule { }
在您的View/Html中使用它,如下所示
{{ createdDate | dateFormat: 'MMMM Do YYYY, h:mm:ss a'}}
希望这能有所帮助。,
当您需要使用它时,您必须在@component:中指定它
@Component({
moduleId: module.id,
templateUrl: './xyz.component.html',
styleUrls: ['./xyz.component.css'],
pipes: [MomentPipe],
directives: [...]
})
public export ...
并以这种方式在html中使用它:
{{now | momentPipe:'YYYY-MM-DD'}}
顺便说一句,这是我写管道的方式:
import {Pipe, PipeTransform} from '@angular/core';
import * as moment from 'moment';
@Pipe({
name: 'momentPipe'
})
export class MomentPipe implements PipeTransform {
transform(value: Date|moment.Moment, ...args: any[]): any {
let [format] = args;
return moment(value).format(format);
}
}
尝试低于
export class MomentPipe implements PipeTransform {
transform(date, format) {
return moment(date).format(format);
}
}
使用ngx矩-这是一个出色的moment.js
包装器,专为Angular 2+设计。
它几乎可以开箱即用地做任何你需要的事情,在你的情况下:
{{time.bookingTime.iso | amDateFormat:'MMMM Do YYYY, h:mm:ss a'}}
相关文章:
- Datetime格式为Friendly Time.Moment JS输出错误
- 问题用moment JS制作一个简单的时间表
- 针对重复发生的事件,使用moment.js防止DST偏移
- 如何在moment.js中只比较日期
- 如何用moment.js列出两个日期之间的所有月份
- 用Jquery map和moment js制作一个简单的时间线
- 如何使用Moment JS获得时间
- 如何获得一个只有时间的moment.js日期对象
- 使用moment.js获取时间分区的偏移日期对象
- Moment js and IOS
- moment.js在两个时区格式的日期之间存在差异
- 使用Moment添加天数.JS
- moment js,将EST字符串转换为UTC
- Moment.js不接受变量作为参数
- Moment JS:忽略年份的天数差异
- 使用moment.js获取月份和年份中的所有日期
- moment.js年份/数字格式,阿拉伯语言环境
- 尝试设置时间时Moment JS Deprecation警告
- Moment.js与上午至下午的时间范围进行比较
- Moment.js-Moment().format()创建无效日期