Dart Duration abs()
Syntax & Examples
Duration.abs() method
The `abs` method in Dart returns a new Duration representing the absolute value of a given Duration object.
Syntax of Duration.abs()
The syntax of Duration.abs() method is:
Duration abs()
This abs() method of Duration returns a new Duration representing the absolute value of this Duration.
Return Type
Duration.abs() returns value of type Duration
.
✐ Examples
1 Calculating absolute value of a positive Duration
In this example,
- We create a Duration object
duration1
with 2 days and 3 hours. - We call the
abs()
method to get its absolute value as a new Duration object. - We then print the absolute Duration 1 to standard output.
Dart Program
void main() {
Duration duration1 = Duration(days: 2, hours: 3);
Duration absDuration1 = duration1.abs();
print('Absolute Duration 1: $absDuration1');
}
Output
Absolute Duration 1: 51:00:00.000000
2 Calculating absolute value of a negative Duration
In this example,
- We create a Duration object
duration2
with -10 hours and 30 minutes. - We call the
abs()
method to get its absolute value as a new Duration object. - We then print the absolute Duration 2 to standard output.
Dart Program
void main() {
Duration duration2 = Duration(hours: -10, minutes: 30);
Duration absDuration2 = duration2.abs();
print('Absolute Duration 2: $absDuration2');
}
Output
Absolute Duration 2: 9:30:00.000000
3 Calculating absolute value of a negative Duration in minutes
In this example,
- We create a Duration object
duration3
with -150 minutes. - We call the
abs()
method to get its absolute value as a new Duration object. - We then print the absolute Duration 3 to standard output.
Dart Program
void main() {
Duration duration3 = Duration(minutes: -150);
Duration absDuration3 = duration3.abs();
print('Absolute Duration 3: $absDuration3');
}
Output
Absolute Duration 3: 2:30:00.000000
Summary
In this Dart tutorial, we learned about abs() method of Duration: the syntax and few working examples with output and detailed explanation for each example.