2016-11-05 22 views
0

我發現很難用時區顯示一組日期(字符串數據類型)。如何以'Mon,Sep 12 2:30 AM AEDT'或當地時區的格式顯示日期(字符串類型)?

這是我的日期JSON:

{ 
    "startDate": "2016-09-04T21:00:00Z", 
    "endDate": "2016-09-05T05:00:00Z" 
} 

我不能表現出來這樣'Mon, Sep 05 2:30AM IST',即根據用戶的位置來顯示時區。我嘗試使用內置DatePipe如下:

<div class="col-xs-12"> {{ startDate | date:'EEE, MMM dd h:mma Z' }}</div> 

但是這給:

Mon, Sep 05 2:30AM GMT+5:30 
+0

您是否嘗試過使用內建的['DatePipe'](https://angular.io/docs/ts/latest/api/common/index/DatePipe-pipe.html)?你在任何時候都將該字符串轉換爲JS日期對象嗎?你做了什麼,當你做了什麼,你能給[mcve]嗎? – jonrsharpe

+0

這是我如何使用內置管 -

{{ startDate | date:'EEE, MMM dd h:mma Z' }}
where startDate =「2016-09-04T21:00:00Z」; 這就是我如何獲得UI「週一,9月5日上午2:30 GMT + 5:30」 –

+0

請[編輯]問題。 – jonrsharpe

回答

0

根據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,它提供了很多功能來處理日期和時間。

+0

它工作像魔術!非常感謝:) –

+0

還有一個查詢,關於我們如何編寫測試日期格式的業力? –

+0

@AryaK你在編寫測試時遇到了一些具體問題?您可以直接使用不同的輸入和預期輸出調用變換方法。 – jonrsharpe

相關問題