【问题标题】:How do I set my HTML5 datetime-local input field to the current local date-time in Angular?如何将我的 HTML5 日期时间本地输入字段设置为 Angular 中的当前本地日期时间?
【发布时间】:2017-11-03 09:53:13
【问题描述】:

我在这里浏览了一些旧问题,但其中大部分是关于 Angular 2 beta/RC 版本的,它们没有附带日期管道。

我从 2015 年 12 月开始与 THIS answer 联系更紧密,它提出了以下解决方案:

<input type="datetime-local" [ngModel]="datetime" (ngModelChange)="datetime = $event" name="datetime">

constructor() {
    this.datetime = new Date().toISOString().slice(0, 16);
}

这几乎可以正常工作,因为它将当前日期时间输出为:02-06-2017 05:02 AM,其中日期正确但时间不正确。这里的本地日期时间是02-06-2017 10:48 AM

我没有在 Angular 的任何地方配置默认时区。我需要这样做还是有更好的解决方案来解决这个问题?另外,也许可以实现内置的date pipe,但我不确定如何实现。

【问题讨论】:

    标签: html angular datetime


    【解决方案1】:

    这是一个plnkr 演示

    要显示当前的本地日期时间,您只需创建一个类似 ISO 的字符串,如下所示:

    this.datetime = this.datetime.getFullYear() + '-' + 
    ("0" + (this.datetime.getMonth() + 1)).slice(-2) 
    + '-' + ("0" + this.datetime.getDate()).slice(-2) 
    + 'T' + this.datetime.getHours() + ':' + this.datetime.getMinutes();
    

    如果您有任何问题,请随时发表评论并告诉我。

    【讨论】:

    • 对不起,我忘了重新检查。这只会正确输出时间而不是日期。在 6 月 4 日,它显示为 5 月 5 日。因此,月份比应有的值少 1,而日期比应有的值多 1。如果我将 1 添加到 getMonth 为 datetime.getMonth()+1 并从 getDate 中删除 +1datetime.getDate(),则输入字段不接受它。控制台报错:The specified value "2017-51-04T15:30" does not conform to the required format. The format is "yyyy-MM-ddThh:mm" followed by optional ":ss" or ":ss.SSS".。朋友,有什么想法吗?
    • 抱歉@anonym 已将 1 添加到 getDate() 而不是 getMonth()。现在它是固定的。如果您还有问题,请尝试让我知道
    • 就像我在评论中提到的那样,我确实尝试将 1 添加到 getMonth() 而不是 getDate(),它报告了错误。但现在它就像一个魅力!再次非常感谢。
    猜你喜欢
    • 2015-12-17
    • 1970-01-01
    • 2019-01-18
    • 2017-04-22
    • 2012-12-21
    • 2021-11-08
    • 2021-10-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多