【问题标题】:How to get date and time in mm-dd-yyy hh-mm-ss in typescript?如何在打字稿中以 mm-dd-yyyy hh-mm-ss 获取日期和时间?
【发布时间】:2018-08-02 07:13:49
【问题描述】:

目前,我正在获取以下格式的日期时间 'mm/dd/yyyy, hh:mm:ss'。 如何以以下格式获取它'mm-dd-yyyy hh-mm-ss'。

如何在不使用任何库的情况下实现这一点,最好是通过将一些参数传递给函数本身?

以下是当前正在使用的代码(在 Angular 5 中)

console.log(new Date().toLocaleString(undefined, { hour12: false }));

【问题讨论】:

  • 嗨,您提供的问题的解决方案是我首先使用的解决方案。但是,我想将输出格式化为特定格式,而不使用 momentjs 或编写任何特定的格式化函数。谢谢:)
  • @GONZALOPANIAGUA - 它不重复,它对角度和角度的问题有 DatePipe 进行这种格式化..不需要长的 javascript 代码

标签: javascript typescript date angular5


【解决方案1】:

利用 Angular 框架提供的 DatePipe

{{ strDate | date :'MM-dd-yyyy hh-mm-ss' }

或者在代码中你可以这样做

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

@Component({
 selector: 'test-component',
  templateUrl: './test-component.component.html'
})
class TestComponent {

  constructor(private datePipe: DatePipe) {}

  formatDate(date= new Date()) {
    return this.datePipe.transform(date,'MM-dd-yyyy hh-mm-ss' );
  }
}

在这里查看:DatePipe

【讨论】:

  • 我试过这个,但它在 DatePipe() 中抛出错误“预期 1 个参数,但得到 0”。有什么帮助吗?
  • This answer 有您需要的信息。 TL;DR:将其注入您的组件/服务中。
  • 谢谢@Robby Cornelissen。您的意见帮助我解决了错误。
  • 感谢@PranayRana 的解决方案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-02-17
  • 2020-05-10
  • 2016-07-24
  • 1970-01-01
  • 2023-03-04
  • 1970-01-01
相关资源
最近更新 更多