diff --git a/FromUnixPipe.spec.ts b/FromUnixPipe.spec.ts new file mode 100644 index 0000000..5febf57 --- /dev/null +++ b/FromUnixPipe.spec.ts @@ -0,0 +1,28 @@ +import 'es6-shim'; +import 'reflect-metadata'; +import * as moment from 'moment'; +import {FromUnixPipe} from './FromUnixPipe'; +import {DateFormatPipe} from './DateFormatPipe'; + +describe('FromUnixPipe', () => { + describe('#transform', () => { + it('should parse a unix timestamp number to moment', () => { + const pipe = new FromUnixPipe(); + const result = pipe.transform(1456263980); + expect(result).toEqual(moment.unix(1456263980)); + }); + + it('should parse a unix timestamp string to moment', () => { + const pipe = new FromUnixPipe(); + const result = pipe.transform('1456263980'); + expect(result).toEqual(moment.unix(1456263980)); + }); + + it('should format a unix timestamp', () => { + const unixPipe = new FromUnixPipe(), + datePipe = new DateFormatPipe(); + const result = datePipe.transform(unixPipe.transform(1456263980), ['hh:mmA']); + expect(result.length).toEqual(7); + }); + }); +}); diff --git a/FromUnixPipe.ts b/FromUnixPipe.ts new file mode 100644 index 0000000..e7f2893 --- /dev/null +++ b/FromUnixPipe.ts @@ -0,0 +1,14 @@ +/* angular2-moment (c) 2015, 2016 Uri Shaked / MIT Licence */ + +import {Pipe, ChangeDetectorRef, PipeTransform} from 'angular2/core'; +import * as moment from 'moment'; + +@Pipe({ name: 'amFromUnix', pure: false }) +export class FromUnixPipe implements PipeTransform { + transform(value: any, args?: string[]): any { + if (typeof value === 'string') { + value = +value; + } + return moment.unix(value); + } +} diff --git a/README.md b/README.md index 04fb2df..74c739f 100644 --- a/README.md +++ b/README.md @@ -68,6 +68,22 @@ import {DateFormatPipe} from 'angular2-moment'; Prints `Last updated: January 24, 2016` +## amFromUnix pipe + +``` typescript +import {DateFormatPipe, FromUnixPipe} from 'angular2-moment'; + +@Component({ + selector: 'app', + pipes: [DateFormatPipe, FromUnixPipe], + template: ` + Last updated: + ` +}) +``` + +Prints `Last updated: 01:46PM` + Complete Example ---------------- diff --git a/package.json b/package.json index ff68074..56b0298 100644 --- a/package.json +++ b/package.json @@ -21,6 +21,8 @@ "TimeAgoPipe.js.map", "TimeAgoPipe.d.ts", "TimeAgoPipe.ts", + "FromUnixPipe.d.ts", + "FromUnixPipe.ts", "CHANGELOG.md" ], "scripts": {