【问题标题】:Date Conversion in javascript to (d MMMMM yyyy HH:mm am) without momentjsjavascript中的日期转换为(d MMMMM yyyy HH:mm am),没有momentjs
【发布时间】:2020-02-07 16:39:16
【问题描述】:

我有这种格式的日期“2020-02-07T16:13:38.22”我想将其转换为“d MMMMM yyyy HH:mm a”而不使用momentjs。

以下方法用于转换日期

const options = {
  day: "numeric",
  month: "long",
  year: "numeric",


}

var date1 = new Date("2020-02-07T16:13:38.22").toLocaleDateString("en-US", options);
const options1 = {
  hour12: true,
  hour: "numeric",
  minute: "2-digit",

}

var date2 = new Date("2020-02-07T16:13:38.22").toLocaleTimeString("en-US", options1);
var res = date1 + ', ' + date2;



console.log(res)

上面的代码给出了结果“2020 年 2 月 7 日,下午 4:13”,但我需要“2020 年 2 月 7 日下午 4:13”,即首先是日期,然后是月份、年份和时间,我尝试的代码更长,请帮忙我在所需的结果中。

【问题讨论】:

  • 用getFullYear()、getMonth()等提取年、月等,然后组装成一个字符串?
  • 为什么要这样做呢?日期处理库正好可以帮助您生成自定义格式的日期。当然,如果您知道自己在做什么,您也可以不使用它来完成它,但它总是有帮助不重新发明轮子。
  • 可能更容易创建月份枚举并使用 javascript 日期函数自己构建它
  • @Vinuta:有没有适合你的答案?如果是,请考虑接受/支持他们。 What should I do when someone answers my question?

标签: javascript angular


【解决方案1】:

在 Angular 中,我发现为复杂的日期格式注入日期管道最容易

import { DatePipe } from '@angular/common';
import { Component, OnInit } from '@angular/core';

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

  formatted: string;  

  ngOnInit(): void {
    const d = new Date();
    this.formatted = this.datePipe.transform(d, 'd MMMM yyyy h:mm a');
  }
}

工作示例:stackblitz

注意,我通常会在 html 中对其进行格式化,但看起来您要求的是打字稿解决方案。

【讨论】:

    【解决方案2】:

    您可以使用 date 管道:

    {{'2020-02-07T16:13:38.22' | date:'d LLLL yyyy h:mm a'}}
    

    日期格式的更多细节可以在Date Pipe Angular docs找到。

    【讨论】:

      【解决方案3】:

      您会做这样的事情,但您需要将小时转换为 12 小时而不是 24 小时格式。或者,如果它在 HTML 中使用,请使用如上所述的角度管道。

      const event = new Date(Date.UTC(2012, 11, 20, 3, 0, 0));
      const months =  ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']
      
      var test =  event.getDate()  + ' ' + months[event.getMonth()] + ' ' + event.getFullYear() + ' ' + event.getHours() + ':' + event.getMinutes()
      
      console.log(test)
      

      【讨论】:

        猜你喜欢
        • 2012-06-07
        • 1970-01-01
        • 2022-12-01
        • 2016-05-20
        • 2013-05-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多