TypeScript Date getFullYear()

In this chapter, we will explore the Date.getFullYear() method in TypeScript. This method returns the year of the specified date according to local time. Understanding how to use Date.getFullYear() is useful for extracting the year from a date object.

Table of Contents

  1. Definition
  2. Syntax
  3. Examples
  4. Conclusion

1. Definition

The Date.getFullYear() method returns the year of the specified date according to local time. This method is particularly useful for working with dates in a standard format.

2. Syntax

dateObj.getFullYear(); 

Parameters

The Date.getFullYear() method does not take any parameters.

Return Value

The method returns a four-digit number representing the year of the given date according to local time.

3. Examples

Let’s look at some examples to understand how Date.getFullYear() works in TypeScript.

Example 1: Basic Usage

In this example, we use Date.getFullYear() to get the year from a specific date.

let date = new Date('2024-07-15'); let year = date.getFullYear(); console.log(year); // Output: 2024 

Example 2: Getting the Current Year

In this example, we use Date.getFullYear() to get the current year.

let today = new Date(); let currentYear = today.getFullYear(); console.log(currentYear); // Output: The current year, e.g., 2024 

Example 3: Using Date.getFullYear() with Different Dates

In this example, we use Date.getFullYear() to get the year for different dates.

let date1 = new Date('2000-01-01'); let date2 = new Date('1995-12-25'); console.log(date1.getFullYear()); // Output: 2000 console.log(date2.getFullYear()); // Output: 1995 

Example 4: Using Date.getFullYear() with a Date Object

In this example, we use Date.getFullYear() with a date object created from the current date and time.

let date = new Date(); let year = date.getFullYear(); console.log(year); // Output: The current year 

Example 5: Using Date.getFullYear() with Future Dates

In this example, we use Date.getFullYear() to get the year for future dates.

let futureDate = new Date('2050-05-20'); console.log(futureDate.getFullYear()); // Output: 2050 

Example 6: Using Date.getFullYear() with Past Dates

In this example, we use Date.getFullYear() to get the year for past dates.

let pastDate = new Date('1980-11-15'); console.log(pastDate.getFullYear()); // Output: 1980 

4. Conclusion

In this chapter, we explored the Date.getFullYear() method in TypeScript, which is used to return the year of the specified date according to local time. We covered its definition, syntax, parameters, return value, and provided several examples to demonstrate its usage. Understanding how to use Date.getFullYear() effectively can help in various scenarios where extracting the year from a date object is required.

Leave a Comment

Scroll to Top