【问题标题】:How to get the current year using typescript in angular6如何在angular6中使用打字稿获取当前年份
【发布时间】:2019-02-03 19:02:36
【问题描述】:

如何在angular6中使用typescript获取当前年份

currentYear:Date;
this.currentYear=new Date("YYYY");
alert(this.currentYear);

显示无效日期

【问题讨论】:

    标签: angular typescript angular6


    【解决方案1】:

    试试,

     alert((new Date()).getFullYear());

    【讨论】:

      【解决方案2】:

      你可以试试这个:

      在 app.component.ts.

      export class AppComponent  {
        anio: number = new Date().getFullYear();
      }
      

      在 app.component.html 中

      {{ anio }}
      

      我让你来一场 Stackblitz。

      https://stackblitz.com/edit/angular-byvzum

      【讨论】:

        【解决方案3】:

        因为年份是数字。

         currentYear: number=new Date().getFullYear();
        

        【讨论】:

          【解决方案4】:

          在导入部分,

          import * as moment from 'moment'
          

          在 ngOnInit,

          ngOnInit(){
          this.date = moment(new Date()).format('YYYY');
          console.log(moment(new Date()).format('YYYY'));
          }
          

          【讨论】:

          • 这太过分了
          【解决方案5】:

          试试这个?

          year = new Date().getFullYear()
          console.log(this.year) // output 2020
          

          【讨论】:

            【解决方案6】:

            在javascript中,我们可以使用getFullYear()从日期对象中获取年份。

            currentYear: Date;
            ngOnInit() {
              this.currentYear = new Date("2017");
              console.log(this.currentYear.getFullYear());
            }
            

            请参阅此页面以获取所有日期对象methods

            【讨论】:

            • 您自己设置年份然后检索它。
            【解决方案7】:

            使用矩库:

            import * as moment from 'moment'
            
            moment().year(); // current year
            

            当然你也可以使用这个代码:

            moment().format('YYYY'); // current year
            

            【讨论】:

              【解决方案8】:

              这个很简单。

              在 .ts 文件中使用以下函数。

                currentYearLong(): number {
                return new Date().getFullYear();
                }
              

              现在在 html 中使用大括号来访问年份编号。

              <footer class="deep-color white-text center">
              <p class="flow-text">great company &copy; {{currentYearLong()}}</p>
              </footer>
              

              【讨论】:

                猜你喜欢
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 2010-11-10
                • 2018-06-03
                • 2011-08-25
                • 2014-07-20
                相关资源
                最近更新 更多