Background
It didn't use a time zone format of datetime in database, data has only one time zone.
a. Columns:
b. Data:
So I'll define a custom DatePipe to extend DatePipe in my source code of Angular.
How to implement?
1. Create a pipe class of Angular called MyDatePipe.
Output format: { yyyy/MM/dd HH:mm:ss }
import { DatePipe } from '@angular/common';
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'myDate',
standalone: true
})
export class MyDatePipe extends DatePipe implements PipeTransform {
override transform(value: any, args?: any): any {
let myDate = new Date(value);
myDate.setHours(myDate.getHours() + args);
return super.transform(myDate, 'yyyy/MM/dd HH:mm:ss');
}
}
2. Using it in your component
a. Component
providers: [MyDatePipe],
imports: [MyDatePipe]文章来源:https://www.toymoban.com/news/detail-679914.html
import { Component, OnInit, ChangeDetectionStrategy } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { TokenKey, TokenPre } from '@app/config/constant';
import { WindowService } from '@app/core/services/common/window.service';
import { NzButtonModule } from 'ng-zorro-antd/button';
import { NzInputModule } from 'ng-zorro-antd/input';
import { MyDatePipe } from '../../pipes/my-datepipe';
@Component({
selector: 'app-pages-empty',
templateUrl: './empty.component.html',
changeDetection: ChangeDetectionStrategy.OnPush,
standalone: true,
providers: [MyDatePipe],
imports: [NzButtonModule, NzInputModule, FormsModule, MyDatePipe]
})
export class EmptyComponent implements OnInit {
token?: string;
srvDate: Date = new Date();
srvOffsetOfTimeZone: number = 8; // offset of server time zone
userOffsetOfTimeZone: number = -5.5; // offset of user time zone
constructor(private windowServe: WindowService, private myDatePipe: MyDatePipe) {}
ngOnInit(): void {}
setToken(): void {
this.windowServe.setSessionStorage(TokenKey, TokenPre + this.token);
}
getDate(): void {
this.srvDate = new Date();
const userDate = this.myDatePipe.transform(this.srvDate, -this.srvOffsetOfTimeZone + this.userOffsetOfTimeZone);
console.log(`User date: ${userDate}`);
}
}
b. Html
<button nz-button (click)="getDate()">Show user date</button>
Server time(UTC {{ srvOffsetOfTimeZone }}):{{ srvDate }}
<br />
UTC time(UTC): {{ srvDate | myDate : -srvOffsetOfTimeZone }}
<br />
User time(UTC {{ userOffsetOfTimeZone }}):{{ srvDate | myDate : -srvOffsetOfTimeZone + userOffsetOfTimeZone }}
3. Test result
文章来源地址https://www.toymoban.com/news/detail-679914.html
到了这里,关于[Angular] Custom a DatePipe to support special time zone conversion from user的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!