【问题标题】:How to format date when using primeng calendar?使用primeng日历时如何格式化日期?
【发布时间】:2017-02-13 09:23:22
【问题描述】:

使用 Prime NG p-calendar 组件时如何仅获取日期、月份和年份?当我执行 console.log 我的变量时,我得到了这些值。它显示了这个值:

日期 {2017 年 2 月 1 日星期三 00:00:00 GMT+0700(东南亚标准时间)}

所以我不想要那么久,我只需要 2017 年 1 月 2 日,其余的我不需要。那么我怎样才能得到日期、月份和年份的格式呢?因为我已经这样做了:

这是我的 html :

这是我的 component.ts :

export class report {

  public date: any;


  constructor() {

  }

  public proses(date) {

    console.log(date);

  }

}

【问题讨论】:

  • proses 来自哪里?我正在尝试和你做同样的事情

标签: angular datepicker calendar primeng


【解决方案1】:

您可以像这样使用纯 JavaScript 日期函数来做到这一点:

let day = date.getDate();
let month = date.getMonth() + 1; // add 1 because months are indexed from 0
let year = date.getFullYear();

console.log(day + '/' + month + '/' + year);

另一种方法是使用 toLocaleDateString() 方法,如下所示:

let newDate = date.toLocaleDateString();
console.log(newDate);

或者您可以使用一些库,例如 moment.js,您可以通过以下方式使用它:

let newDate = moment(date).format('DD/MM/YYYY').toString();
console.log(newDate();

两种解决方案都会在控制台记录相同的字符串。

【讨论】:

  • 只是一个小备忘录,获取日期是使用 date.getDate 如果 date.getDay 我会得到那个日期的哪一天
  • @KeVin,你是对的,这就像字面错误。抱歉这个问题,感谢您的洞察力。我刚刚编辑了答案。
【解决方案2】:
import {DatePipe} from '@angular/common';

datePipe.transform(selectedDate, formatInWhichYouWantOutput)

【讨论】:

    猜你喜欢
    • 2017-03-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多