任何希望根据浏览器设置来格式化日期的人,我都创建了管道,用于根据浏览器的语言环境在美国和欧洲之间格式化日期,
date.service-获取浏览器语言环境:
import {
Injectable
} from '@angular/core';
import {
isNullOrUndefined
} from "util";
function _window(): any {
// return the global native browser window object
return window;
}
@Injectable()
export class WindowRef {
get nativeWindow(): any {
return _window();
}
public ln = 'en';
constructor() {
try {
if (!isNullOrUndefined(this.nativeWindow.navigator.language) && this.nativeWindow.navigator.language !== '') {
this.ln = this.nativeWindow.navigator.language;
}
} finally {}
}
}
别忘了将服务导入app.module.ts
基于浏览器区域设置的自定义日期管道:
import {
Pipe,
PipeTransform
} from '@angular/core';
import {
DatePipe
} from '@angular/common';
import {
WindowRef
} from '../services/date/date.service'
@Pipe({
name: 'datepipe',
pure: true
})
export class MyDatePipe extends DatePipe implements PipeTransform {
pattern: string;
constructor(private win: WindowRef) {
super(win.ln);
if (win.ln == "en-IE") {
this.pattern = 'dd/MM/yyyy, HH:mm'
} else {
this.pattern = 'MM/dd/yyyy, h:mm a'
}
}
transform(value: any): string {
return super.transform(value, this.pattern);
}
}
使用管道:
{{search.searchDateTime | datepipe }}
理想情况下,日期格式在管道中应该是动态的,因此它们会自动与浏览器区域设置匹配。因此,如果有人要修改或有更好的解决方案,请添加。