使用 TypeScript 获取当前年份
要在 TypeScript 中获取当前年份:
- 调用
new Date()
构造函数以获取当前日期的日期对象。 - 在日期对象上调用
getFullYear()
方法。 getFullYear
方法将返回一个代表当前年份的数字。
// ?️ const currentYear: number
const currentYear = new Date().getFullYear();
console.log(currentYear); // ?️ 2022
我们使用 Date()
构造函数来获取表示当前日期的 Date 对象。
// ?️ const now: Date
const now = new Date();
console.log(now); // ?️ Thu Feb 17 2022 11:27:54 GMT
now
变量的类型被正确推断为Date
,这使我们能够使用Date
对象实现的任何内置方法。
我们在 Date 对象上调用 Date.getFullYear
方法来获取表示当前年份的数字。
Date 对象的其他常用方法是:
- Date.getMonth – 返回一个介于 0(一月)和 11(十二月)之间的整数,表示给定日期的月份。 是的,不幸的是 getMonth 方法关闭了 1。
- Date.getDate – 返回特定日期的月份日期
在 TypeScript 中使用日期时,我们应该始终牢记 getMonth()
方法返回一个从零开始的值,其中 一月 = 0、二月 = 1 等,直到十二月 = 11。
const now = new Date();
// ?️ const currentYear: number
const currentYear = now.getFullYear();
console.log(currentYear); // ?️ 2022
// ?️ const currentMonth: number
const currentMonth = now.getMonth();
console.log(currentMonth); // ?️ 1 (1 = February)
// ?️ const currentDayOfMonth: number
const currentDayOfMonth = now.getDate();
console.log(currentDayOfMonth); // ?️ 17
getMonth
方法的输出显示 1,即二月,因为该方法返回从零开始的值。
在将输出格式化到访问者的浏览器时,我们经常会看到开发人员将结果加 1。
应该注意的是,我们可以使用 getFullYear()
方法来获取任何有效 Date 对象的年份,现在只是当前日期。
// ?️ const date: Date
const date = new Date('2023-09-24');
// ?️ const currentYear: number
const currentYear = date.getFullYear();
console.log(currentYear); // ?️ 2023
// ?️ const currentMonth: number
const currentMonth = date.getMonth();
console.log(currentMonth); // ?️ 8 (8 = September)
// ?️ const currentDayOfMonth: number
const currentDayOfMonth = date.getDate();
console.log(currentDayOfMonth); // ?️ 24
在此示例中,我们为 2023 年 9 月 24 日创建一个日期,并使用上述所有方法来获取该日期的年、月和日。
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布,任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站。本站所有源码与软件均为原作者提供,仅供学习和研究使用。如您对本站的相关版权有任何异议,或者认为侵犯了您的合法权益,请及时通知我们处理。