typescript 打字稿日期格式
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/46549239/
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
Typescript date formatting
提问by user244394
I am using angular 2/4
How can i format the date into this
2017-10-03T14:51:06.078Z
我正在使用 angular 2/4 如何将日期格式化为这个
2017-10-03T14:51:06.078Z
here is my code below :
这是我的代码如下:
public today: number = Date.now();
console.log("today time " +this.today);
I tried to add
我试着添加
this.today.toLocaleString()
that didn't seem to work
这似乎不起作用
回答by Huupke
You should use the toISOString method:
您应该使用 toISOString 方法:
this.today.toISOString();
But you need to change the type from number to Date:
但是您需要将类型从数字更改为日期:
namespace Testing {
export class Test {
public today: Date;
constructor() {
this.today = new Date();
console.log(this.today.toISOString());
}
}
}
More information can be found here
更多信息可以在这里找到
回答by SwanandNabar
You can do this something like
你可以这样做
this.todayDate = new Date();
this.dateToday = (this.todayDate.getFullYear() + '-' + ((this.todayDate.getMonth() + 1)) + '-' + this.todayDate.getDate() + ' ' +this.todayDate.getHours() + ':' + this.todayDate.getMinutes()+ ':' + this.todayDate.getSeconds());
You can check with console log,
您可以查看控制台日志,
console.log('today date', this.dateToday);
The output will be
输出将是
today date 2017-10-3 10:38:10
Explaination: "this.dateToday" is a variable of type any which will store the date as you want.
解释:“this.dateToday”是一个any类型的变量,它将根据需要存储日期。
You need to get individual year, month, date and the time as well and concat it together. There are many more date methods you can check online or in your IDE.
您还需要获取单独的年、月、日期和时间,并将它们连接在一起。您可以在线或在 IDE 中查看更多日期方法。