【问题标题】:How to get Current Month and Year in string format in Angular?如何在Angular中以字符串格式获取当前月份和年份?
【发布时间】:2019-06-22 06:47:03
【问题描述】:

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

我需要在我的 Angular .ts 文件中使用它。不在 HTML 视图文件中。

【问题讨论】:

标签: javascript angular ionic-framework


【解决方案1】:

你可以使用内置的日期管道:

{{date | date:'MM-dd'}}

并传递您自己的格式。
更新
尝试类似 JS-only 的解决方案:

m = new Date().getMonth().toString() + 1;
y = new Date().getFullYear().toString();
return m + '-' + y;

【讨论】:

  • 它适用于 html 文件。但我想在我的 .ts 文件中格式化日期。
  • 我会告诉你和接受的答案一样的,所以我认为问题已经为你解决了吗?
【解决方案2】:

你可以使用Date():

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

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

更新:

要根据相关的post 添加前导 0,您可以这样做:'0' + (new Date().getMonth() + 1).toString().slice(-2)

解释:

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

以 sn-p 为例:

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>

【讨论】:

  • @AbhijitM.Abhi 同样,如果你做一些研究,stackoverflow.com/questions/3605214/…
  • @Mukyuu 你能再检查一下你的答案吗?在一月份是正确的。但是,在今年二月,它没有得到当前月份和年份。希望您能更新代码。
  • 完成,这是 ( 错误包装。我的错。
  • 那太好了,我的伙伴。
【解决方案3】:

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

1)DatePipe:

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)formatDate

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);
  }
}

【讨论】:

    猜你喜欢
    • 2012-06-12
    • 1970-01-01
    • 2017-10-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-12
    • 1970-01-01
    相关资源
    最近更新 更多