【问题标题】:How to convert Date to String into the format yyyy-mm-dd in typescript [duplicate]如何在打字稿中将日期转换为字符串格式 yyyy-mm-dd [重复]
【发布时间】:2019-01-31 09:05:02
【问题描述】:

如何在 typescript 中将 Date 转为 String 格式 yyyy-mm-dd

现在我得到的日期是 2017 年 3 月 24 日星期五 00:00:00 GMT-0400(东部夏令时间)

我只需要 "2017-03-24" 格式的日期 从那开始,没有任何时区和时区转换

【问题讨论】:

  • 向我们展示您目前拥有的代码
  • 如果你使用 Angular,你应该使用 Date 管道。看看这个问题,几乎是一样的(假设你使用的是 Angular):stackoverflow.com/questions/35754586/…

标签: angular typescript date


【解决方案1】:

假设您使用的是 Angular,您可以将 DatePipe 或 FormatDate 导入到您的 component.ts 中来处理它。您可以阅读有关可以作为参数传递的各种date/time formats 的更多信息。

1) 日期管道:

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

export class SampleComponent implements OnInit {   

constructor(private datePipe: DatePipe) {}

  transformDate(date) {
    return this.datePipe.transform(date, 'yyyy-MM-dd');
  }
}

不要忘记将 DatePipe 添加到模块中的提供程序。

providers: [DatePipe]

2) 格式日期:

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

export class SampleComponent implements OnInit {

  constructor(@Inject(LOCALE_ID) private locale: string) {}

  transformDate(date) {
    return formatDate(date, 'yyyy-MM-dd', this.locale);
  }
}

【讨论】:

  • 管道不能被注入,它们必须被实例化(或实例化然后通过令牌或工厂注入)
  • 我尝试了第一个可行的方法。谢谢 - @wentjun
  • 酷,@Shiny!祝你的项目一切顺利,伙计!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-05-19
  • 2016-04-17
相关资源
最近更新 更多