如何在 ANGular 16/17 中将日期从 UTC 转换为本地时间

问题描述 投票:0回答:1

我从后端获取日期,日期以 UTC 格式存储,但我希望它采用本地时间或 IST

没有找到任何相关的东西,找到我下面的代码,日期转换也不起作用

{{item.capturedDate |日期:"MMM dd, yyyy 'at'hh:mm a" }}
angular typescript utc localtime
1个回答
0
投票

在 Angular 中,您可以使用内置的 DatePipe 将 UTC 时间转换为本地时间。您还可以使用 Date 构造函数和 toLocaleString() 方法来实现此目的。以下是您可以使用的两种方法:

import { DatePipe } from '@angular/common';

// Inside your component or service
export class YourComponentOrService {
  constructor(private datePipe: DatePipe) {}

  convertUTCtoLocal(utcDate: string): string {
    const localDate = this.datePipe.transform(utcDate, 'medium', '+0530');
    return localDate;
  }
}

使用日期构造函数:

export class YourComponentOrService {
  convertUTCtoLocal(utcDate: string): string {
    const date = new Date(utcDate);
    const localDate = date.toLocaleString('en-IN', {timeZone: 'Asia/Kolkata'});
    return localDate;
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.