如何在 Angular 中将时间转换为这种格式 YYYY-MM-DDThh:mm:ssTZD?

问题描述

我们使用 java 作为后端,其中我们使用 ISO 8601。要传递相同的内容,我需要将日期转换为相同的格式。

在java中我们使用

DateFormat iso8601 = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssXXX");

类似如何在 Angular/TypeScript 中将日期转换为完全相同的格式

我附上一张图片,供您参考日期格式。请看图。

enter image description here

解决方法

您需要在组件中使用 DatePipe

app.component.ts

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

@Component({
  selector: 'my-app',templateUrl: './app.component.html',styleUrls: [ './app.component.css' ],providers: [DatePipe]
})
export class AppComponent  {
  today;
  constructor(
    private datePipe:DatePipe
  ){
      this.today = this.datePipe.transform( new Date(),'yyyy-MM-dd  h:mm:ssZZZZZ');
  }
}

对于任何其他日期格式,请在此处查看:https://angular.io/api/common/DatePipe

工作 stackblitz 示例:https://stackblitz.com/edit/angular-datepipe-in-component-u8bzre?file=src/app/app.component.ts

,

请参考以下链接,我认为它应该符合您的目的

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString

toISOString() 方法以简化的扩展 ISO 格式 (ISO 8601) 返回一个字符串

let today = new Date('05 October 2011 14:48 UTC')

console.log(today.toISOString())  // Returns 2011-10-05T14:48:00.000Z
,

Convert an ISO date to the date format yyyy-mm-dd in JavaScript

作为参考,这是我使用的。我选择在我的示例中省略小时、分钟和秒。不过,它运行良好。不应该是特定于角度的,所以它应该像普通的 javascript 一样工作。

var theDate = new Date();
var dd = String(theDate.getDate()).padStart(2,'0');
var mm = String(theDate.getMonth() + 1).padStart(2,'0'); //January is 0!
var yyyy = theDate.getFullYear();

theDate = yyyy + '-' + mm + '-' + dd;
,

我发现了如何创建我们想要的格式。

我们可以使用下面的代码来获得所需的输出。

let date: string = "" 
date = this.datepipe.transform(new Date(),"yyyy-MM-ddThh:mm:ssZZZZZ")

您也可以用您的日期变量替换 new Date()。

enter image description here