📜  dateTime.now addyears dart (1)

📅  最后修改于: 2023-12-03 15:00:21.438000             🧑  作者: Mango

DateTime.now().addYears in Dart

Overview

DateTime.now().addYears is a method in Dart language that allows you to add a specified number of years to the current date and time. It returns a new DateTime object with the added years.

Syntax

The syntax for using DateTime.now().addYears is:

DateTime.now().add(Duration(days: yearsToAdd * 365));

Where yearsToAdd is the number of years you want to add.

Parameters

This method accepts a single parameter:

  • yearsToAdd (required): The number of years to add to the current date and time. It must be an integer value.
Return Value

The addYears method returns a new DateTime object with the added years. The original DateTime object is not modified.

Example Usage

Here's an example that demonstrates how to use DateTime.now().addYears:

void main() {
  DateTime currentDateTime = DateTime.now();
  int yearsToAdd = 2;
  
  DateTime newDateTime = currentDateTime.add(Duration(days: yearsToAdd * 365));
  
  print("Current Date and Time: $currentDateTime");
  print("New Date and Time: $newDateTime");
}

Output:

Current Date and Time: 2022-01-01 10:30:45.123456
New Date and Time: 2024-01-01 10:30:45.123456

In this example, we add 2 years to the current date and time using DateTime.now().addYears. The newDateTime variable holds the updated date and time.