如何在 Angular 中以字符串格式获取当前月份和年份?

新手上路,请多包涵

预期输出:字符串中的 01-201902-2019

我的 Angular .ts 文件中需要这个。不在 HTML 视图文件中。

原文由 Abhijit Mondal Abhi 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 577
2 个回答

您可以使用 Date()

this.curdate = (new Date().getMonth() + 1).toString() + '-' + new Date().getFullYear().toString();

请注意 new Date().getMonth() 从 0 到 11 开始,因此您需要 +1 使其成为 1 到 12。

更新:

要根据相关 帖子 添加前导 0,您可以执行以下操作: '0' + (new Date().getMonth() + 1).toString().slice(-2)

解释:

由于 '0' 不是数字而是字符串,当您添加( + )与另一个字符串时,它将被连接起来。然后 .slice(-2) 给我们字符串的最后两个字符。如果它是个位数那么它将是 0x 月,如果它是两位数那么它将是 0 + xx 返回的月份。

例如,请参见代码段:

 var d = '0' + (new Date().getMonth() + 1).toString().slice(-2) + '-' + new Date().getFullYear().toString();
document.getElementById("demo").innerHTML = d;
 <p id="demo"></p>

或者,如果您不想在两位数月份(10 月、11 月、12 月)尾随 0,您可以根据月份数字长度进行一些检查: (new Date().getMonth() + 1).length > 1 ? new Date().getMonth() + 1 : '0' + (new Date().getMonth() + 1)

 var month = (new Date().getMonth() + 1).length > 1 ? new Date().getMonth() + 1 : '0' + (new Date().getMonth() + 1);
var date = (month).toString().slice(-2) + '-' + new Date().getFullYear().toString();
document.getElementById("demo").innerHTML = date;
 <p id="demo"></p>

原文由 Mukyuu 发布,翻译遵循 CC BY-SA 4.0 许可协议

或者,您可以将 DatePipeFormatDate 导入您的 component.ts。

1) 日期管道

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

export class SampleComponent implements OnInit {

constructor(private datePipe: DatePipe) {}

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

不要忘记将 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, 'MM-yyyy', this.locale);
  }
}

原文由 wentjun 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题