【问题标题】:Input type date is not working with some values angular 6输入类型日期不适用于某些值 angular 6
【发布时间】:2019-06-21 03:40:38
【问题描述】:

我有一个 html5 的日期输入,我在其中使用日期选择器,但我的值包含一些额外的字符,例如“2019-01-01T23-00-11”,这不是第一次出现在文本框中,这里是代码如下

app.component.html

<div style="text-align:center">
  <input  type="date" [(ngModel)]="name" value="name">
  <p>Value: {{ name }}</p>
</div>

app.component.ts

import { Component } from "@angular/core";

@Component({
  selector: "app-root",
  templateUrl: "./app.component.html",
  styleUrls: ["./app.component.css"]
})
export class AppComponent {
  name: string = '2019-01-01T23-00-11';
  //name: string = '2019-01-01';
  ngOnInit() {

  }

}

【问题讨论】:

  • 我建议使用日期/日期时间选择器控件,而不是浏览器中的内置控件,因为浏览器的实现方式不同(或没有实现方式)。
  • 日期字符串格式好像不正确
  • 我可以在这里使用任何简单的方法或控件吗?
  • 对于初学者来说,修复字符串中的值,它不是根据ISO8601 标准格式化的,所以浏览器和您可能尝试使用的任何控件都会有问题。

标签: html angular typescript


【解决方案1】:

如果您将日期输入更改为本地日期时间,然后将您的字符串更改为以冒号分隔的时间而不是连字符分隔的时间,您将可以工作。这将在 Chrome 中运行。尚未测试所有其他浏览器。

// In the html
<input  type="datetime-local" [(ngModel)]="name" value="name">

// In app.component.ts
name = `2019-01-01T23:00:11`

如果您这样做,日期和时间将显示在浏览器中。

【讨论】:

【解决方案2】:

您可以在获取值之前对其进行格式化

getDate(){

   let d = new Date(this.name)

     return `${d.getFullYear()}-${d.getMonth()}-${d.getDate()}`

   }

HTML

<input  type="date" [(ngModel)]="getDate()" value="name">

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-09-08
    • 2017-07-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多