javascript 如何以角度 2 获取 YYYY-MM-DD 格式的日期
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/46061638/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
how to get date in YYYY-MM-DD format in angular 2
提问by Stacy J
I want to get date in the following format: YYYY-MM-DD.
我想以以下格式获取日期:YYYY-MM-DD。
I wrote a date service in Angular2 based on this question: How do I get the current date in JavaScript?.
我基于这个问题在 Angular2 中编写了一个日期服务: How do I get the current date in JavaScript? .
I wanted to check if it is a correct implementation or if there exists a better way to achieve the goal.
我想检查它是否是正确的实现,或者是否有更好的方法来实现目标。
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;
}
}
回答by Sajeetharan
回答by Kanchan Kumar
The different date format can be achievable through moment.js library. You can just import/add it. and use the following syntax to convert your timestamp to date string.
不同的日期格式可以通过 moment.js 库实现。您可以只导入/添加它。并使用以下语法将时间戳转换为日期字符串。
moment.tz(this.value, 'GMT').format('yyyy-MM-dd HH:mm:ss');
moment.tz(this.value, 'GMT').format('yyyy-MM-dd HH:mm:ss');
Here tz is timezone.
这里 tz 是时区。
回答by arul prince
// 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('-');
}
}

