如何在Angular 2中以YYYY-MM-DD格式获取日期

5

我希望以YYYY-MM-DD的格式获取日期。

我基于以下问题在Angular2中编写了一个日期服务: 如何在JavaScript中获取当前日期?.

我想检查这是否是正确的实现方法,或者是否存在更好的方法来实现目标。

import { Injectable } from '@angular/core';

@Injectable()
export class DateService {
private currentDate = new Date();

    getCurrentDateInApiFormat(): string{
        let day:any = this.currentDate.getDate();
        let month:any = this.currentDate.getMonth() + 1;
        let year:any = this.currentDate.getFullYear();
        let dateInApiFormat: string;

        if(day<10){
           day = '0' + day.toString();
        }
        if(month<10){
            month = '0' + month.toString();
        }
        dateInApiFormat = day + '-' + month + '-' + year.toString();
        return dateInApiFormat;
    }
}
3个回答

8

您可以直接使用Date Pipe来处理日期。

 <p>The time is {{currentDate | date:'yyyy-MM-dd'}}</p>

在 TypeScript 中
export class App {

 currentDate: number = Date.now();

}

DEMO


3
  // To use date service 

   import { Injectable } from '@angular/core';

   @Injectable()

   export class DateService {

      public currentDate = new Date();

       getCurrentDateInApiFormat() {
          const date = currentDate;
          const month = ('0' + (date.getMonth() + 1)).slice(-2);
          const day = ('0' + date.getDate()).slice(-2);

          return [date.getFullYear(), month, day].join('-');
       }
   }    

1
不同的日期格式可以通过moment.js库实现。您只需导入/添加它,然后使用以下语法将时间戳转换为日期字符串:
moment.tz(this.value,'GMT').format('yyyy-MM-dd HH:mm:ss');
这里的tz是时区。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接