In this example, we are going to show you the easiest way to add or subtract duration from DateTime in Dart and Flutter. You will learn to add or subtract durations on days, seconds, minutes, hours, and more. See the example below:
DateTime dt1 = DateTime.parse("2021-12-23 11:47:00");
DateTime dt2 = dt1.add(Duration(seconds: 10));
print(dt2);
//Output: 2021-12-23 11:47:10.000
DateTime dt3 = dt1.add(Duration(minutes: 10, seconds: 30));
print(dt3);
//Output: 2021-12-23 11:57:30.000
DateTime dt4 = dt1.add(Duration(hours: 20));
print(dt4);
//Output: 2021-12-24 07:47:00.000
DateTime dt5 = dt1.add(Duration(days: 20));
print(dt5);
//Output: 2022-01-12 11:47:00.000
DateTime dt1 = DateTime.parse("2021-12-23 11:47:00");
DateTime dt2 = dt1.subtract(Duration(seconds: 10));
print(dt2);
//Output: 2021-12-23 11:46:50.000
DateTime dt3 = dt1.subtract(Duration(minutes: 10, seconds: 30));
print(dt3);
//Output: 2021-12-23 11:36:30.000
DateTime dt4 = dt1.subtract(Duration(hours: 20));
print(dt4);
//Output: 2021-12-22 15:47:00.000
DateTime dt5 = dt1.subtract(Duration(days: 20));
print(dt5);
//Output: 2021-12-03 11:47:00.000
import 'package:flutter/material.dart';
void main() {
runApp( MaterialApp(
home: Home()
));
}
class Home extends StatefulWidget {
@override
State<Home> createState() => _HomeState();
}
class _HomeState extends State<Home> {
@override
Widget build(BuildContext context) {
DateTime dt1 = DateTime.parse("2021-12-23 11:47:00");
return Scaffold(
appBar: AppBar(
title: Text("Add/Subtract Duration from DateTime"),
backgroundColor: Colors.redAccent,
),
body: Container(
alignment: Alignment.center,
padding: EdgeInsets.all(20),
child: Column(
children:[
Text("Date and Time:" + dt1.toString()),
Text("2 days added: " + dt1.add(Duration(days: 2)).toString()),
Text("5 days 4 Hours Added: " + dt1.add(Duration(days: 5, hours: 4)).toString()),
Text("10 days 20 Hours Subtracted: " + dt1.subtract(Duration(days: 10, hours: 20)).toString()),
]
),
)
);
}
}
In this way, you can add or subtract duration from Date and Time in Dart/Flutter.
Please Wait...
No any Comments on this Article