在日期输入元素(html 日期选择器)中将纪元日期时间显示为格式化日期

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

有角度 想要在日期输入元素(html 日期选择器)中将纪元日期时间显示为格式化日期dop show in input using binding 我可以通过使用函数来显示这一点并在输入中设置,但想直接使用绑定来设置它

尝试了多种解决方案,但每个解决方案都在转换为元素后提供手动设置的数据 想要使用数据绑定,因为我们直接在文本视图中使用其他字符串

html angular datetime binding epoch
1个回答
0
投票

创建一个管道来格式化纪元日期时间。

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
  name: 'epochToDateFormatter'
})
export class EpochToDateFormatterPipe implements PipeTransform {

  transform(epochDateTime: number, format: string = 'yyyy-MM-dd'): string {
    const date = new Date(epochDateTime);
    return date.toLocaleDateString(format);
  }

}

您可以通过将不同的格式字符串传递到 epochToDateFormatter 管道来更改日期格式。

import { Component, OnInit } from '@angular/core';
import { EpochToDateFormatterPipe } from './epoch-to-date-formatter.pipe';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {

  epochDateTime: number = 1663761600000;

  constructor(private epochToDateFormatterPipe: EpochToDateFormatterPipe) { }

  ngOnInit() {
  }

}
<input type="date" [(ngModel)]="epochDateTime" [date]="epochDateTime | epochToDateFormatter:'yyyy-MM-dd'">
© www.soinside.com 2019 - 2024. All rights reserved.