如何将“2021-01-19T12:50:00Z”格式化为:2021-01-19 12:50:00

时间:2021-01-19 21:25:42

标签: javascript angular typescript

我正在使用 angular 和 rxjs。

所以我有这个:

  x: console.log(res.map(date => date.dt))

它返回这个:

0: "2021-01-19T12:50:00Z"
1: "2021-01-19T12:51:00Z"
2: "2021-01-19T12:52:00Z"
3: "2021-01-19T12:53:00Z"
4: "2021-01-19T12:54:00Z"
5: "2021-01-19T12:55:00Z"
6: "2021-01-19T12:56:00Z"
7: "2021-01-19T12:57:00Z"
8: "2021-01-19T12:59:00Z"

但这当然是不可读的。

所以我想将其转换为例如:'2021-01-19 12:50:00',

所以:yyyy-MM-dd HH-MM-SS

但是我必须改变什么?

谢谢

3 个答案:

答案 0 :(得分:0)

你也许可以这样做:

    // this is taking a date string, if you are passing the date obj directly then no need to pass it to `new Date()`
    function cleanTheDate(dateStr) {
        return new Date(dateStr).toISOString().
            replace(/T/, ' ').
            replace(/\..+/, '')
    }

答案 1 :(得分:0)

我猜您必须编写自己的日期格式化程序函数。类似的东西:

const formatDate = (inputDate) => {
  return `${inputDate.getFullYear()}-${addLeadingZero(inputDate.getMonth() + 1)}-${addLeadingZero(inputDate.getDate())} ${addLeadingZero(inputDate.getHours())}:${addLeadingZero(inputDate.getMinutes())}:${addLeadingZero(inputDate.getSeconds())}`;
}

const addLeadingZero = (input) => {
  return input < 10 ? `0${input}` : input;
}

console.log(formatDate(new Date()));

答案 2 :(得分:0)

Angular 有自己的 HTML 日期管道和 TS 文件的 formatDate() 函数

嗨,正如我上面提到的,你可以使用 Angular 的内置管道

日期管道:https://angular.io/api/common/DatePipe

formatDate() 函数:https://angular.io/api/common/formatDate

// If you want to format the date in the HTML template

// Syntax
{{ value_expression | date [ : format [ : timezone [ : locale ] ] ] }}


// Example
<p>
  <strong>
     Birthday in format dd/MM/yyyy :
  </strong>
  {{ birthday | date:'dd/MM/yyyy' }}
</p>
-------------------------------------------------------------

// If you want to format the date in the component.ts file

// Syntax
formatDate(value: string | number | Date, format: string, locale: string, timezone?: string): string

// Example
import { formatDate } from '@angular/common';

const format = 'dd/MM/yyyy';
const myDate = '2021-01-20';
const locale = 'en-US';
const formattedDate = formatDate(myDate, format, locale);

相关问题