根據the docs內置DatePipe
時區選項'Z'
的GMT偏移量(,在我案例)或'z'
全名(British Summer Time
)。如果你想有不同的表現,你可以用自定義的管道做,比如:
import { LOCALE_ID, Pipe, PipeTransform, Inject } from '@angular/core';
import { DatePipe } from '@angular/common';
@Pipe({
name: 'customDate'
})
export class CustomDatePipe implements PipeTransform {
datePipe: DatePipe;
constructor(@Inject(LOCALE_ID) private locale: string) {
this.datePipe = new DatePipe(locale);
}
transform(value: any, args?: any): any {
let fullTimezone = this.datePipe.transform(value, 'z');
let rest = this.datePipe.transform(value, 'EEE, MMM dd h:mma');
let timezone = fullTimezone.match(/[A-Z]/g).join('');
return `${rest} ${timezone}`;
}
}
在這裏,我假設你想要的時區表示是英文縮寫,即在大寫字母全時區名稱(B ritish S ummer T ime - > BST)。然後,您可以在HTML中使用該管道:{{ startDate | customDate }}
。這也可以防止您需要在整個代碼庫中重複使用格式,在可能的情況下,您希望每個地方都使用一致的日期格式。
要測試管,在TestBed
設置它:
import { LOCALE_ID } from '@angular/core';
import { ComponentFixture } from '@angular/core/testing';
import { CustomDatePipe } from './custom-date.pipe';
describe('CustomDatePipe',() => {
let pipe: CustomDatePipe;
beforeEach(() => {
TestBed.configureTestingModule({
providers: [
{ provide: LOCALE_ID, useValue: 'en-GB' },
CustomDatePipe
]
});
pipe = TestBed.get(CustomDatePipe);
});
it('should do whatever you want it to do',() => {
expect(pipe.transform('...').toBe('...');
});
});
或者,你可以看看moment-timezone
,它提供了很多功能來處理日期和時間。
您是否嘗試過使用內建的['DatePipe'](https://angular.io/docs/ts/latest/api/common/index/DatePipe-pipe.html)?你在任何時候都將該字符串轉換爲JS日期對象嗎?你做了什麼,當你做了什麼,你能給[mcve]嗎? – jonrsharpe
這是我如何使用內置管 -
請[編輯]問題。 – jonrsharpe