预期输出:字符串中的 01-2019 或 02-2019 。
我的 Angular .ts 文件中需要这个。不在 HTML 视图文件中。
原文由 Abhijit Mondal Abhi 发布,翻译遵循 CC BY-SA 4.0 许可协议
预期输出:字符串中的 01-2019 或 02-2019 。
我的 Angular .ts 文件中需要这个。不在 HTML 视图文件中。
原文由 Abhijit Mondal Abhi 发布,翻译遵循 CC BY-SA 4.0 许可协议
或者,您可以将 DatePipe
或 FormatDate
导入您的 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 许可协议
13 回答13k 阅读
7 回答2.1k 阅读
3 回答1.3k 阅读✓ 已解决
6 回答1.2k 阅读✓ 已解决
2 回答1.4k 阅读✓ 已解决
3 回答1.3k 阅读✓ 已解决
6 回答1.1k 阅读
您可以使用 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
返回的月份。例如,请参见代码段:
或者,如果您不想在两位数月份(10 月、11 月、12 月)尾随 0,您可以根据月份数字长度进行一些检查:
(new Date().getMonth() + 1).length > 1 ? new Date().getMonth() + 1 : '0' + (new Date().getMonth() + 1)