在本教程中,我们将学习如何在TypeScript中使用new Date()
构造函数获得当前年份。
获取当前年份
我们可以在TypeScript中通过调用一个新的Date()构造函数的getFullYear()
方法来获得当前年份。
getFullYear()
方法根据用户的当地时间,以四位数(2022)的格式返回当前年份。
下面是一个例子。
const currentYear = new Date().getFullYear();
console.log(currentYear);
输出。
2022
同样我们可以通过使用getMonth()
,getDate()
方法在TypeScript中获得当前的月份,日期。
下面是一个关于当前月份的例子。
const currentMonth = new Date().getMonth();
console.log(currentMonth); // 8
getMonth()
以数字格式返回月份,从(0-11),其中0
是一月,1
是二月,11是十二月,等等。
下面是一个当前日期的例子。
const currentDate = new Date().getDate();
console.log(currentDate); // 7
getDate()
根据用户的当地时间,返回当前的一个月的日期。