DateTime comparison in dart - flutter

I am trying to sort list of DateTime time elements in ascending order.I have realized normal operators like > or < don't cut it. What is the best way to compare two DateTime variables ?

Simply use the methods isAfter(), isBefore() or isAtSameMomentAs() from DateTime.
Other alternative, use compareTo(DateTime other), as in the docs:
Compares this DateTime object to [other],
returning zero if the values are equal.
Returns a negative value if this DateTime [isBefore] [other]. It returns 0
if it [isAtSameMomentAs] [other], and returns a positive value otherwise
(when this [isAfter] [other]).
Here a code example of sorting dates:
void main() {
var list = [
DateTime.now().add(Duration(days: 3)),
DateTime.now().add(Duration(days: 2)),
DateTime.now(),
DateTime.now().subtract(Duration(days: 1))
];
list.sort((a, b) => a.compareTo(b));
print(list);
}
See it working here.

This is I how understood and implemented the code it will result in true / false in boolean mode.
DateTime valEnd = edate ;
DateTime date =DateTime.now();
bool valDate = date.isBefore(valEnd);

DateTime comparison in dart
DateTime.compareTo(DateTime other):
DateTime dt1 = DateTime.parse("2021-12-23 11:47:00");
DateTime dt2 = DateTime.parse("2018-02-27 10:09:00");
if(dt1.compareTo(dt2) == 0){
print("Both date time are at same moment.");
}
if(dt1.compareTo(dt2) < 0){
print("DT1 is before DT2");
}
if(dt1.compareTo(dt2) > 0){
print("DT1 is after DT2");
}
DateTime.isAtSameMomentAs(DateTime other):
DateTime dt1 = DateTime.parse("2021-12-23 11:47:00");
DateTime dt2 = DateTime.parse("2018-02-27 10:09:00");
if(dt1.isAtSameMomentAs(dt2)){
print("Both DateTime are at same moment.");
}
DateTime.isAfter(DateTime other):
DateTime dt1 = DateTime.parse("2021-12-23 11:47:00");
DateTime dt2 = DateTime.parse("2018-02-27 10:09:00");
if(dt1.isAfter(dt2)){
print("DT1 is after DT2");
}
DateTime.isBefore(DateTime other):
DateTime dt1 = DateTime.parse("2021-12-23 11:47:00");
DateTime dt2 = DateTime.parse("2018-02-27 10:09:00");
if(dt1.isBefore(dt2)){
print("DT1 is before DT2");
}

Related

How to get the next near future value to the current time in a list in Flutter?

I have a store schedule that comes from the server. And I get the current time. I need to find the near future start_time to my current time in the list I am getting. For example, if the current time is 3:00 pm, I need to get the closest start_time, which is 5:00 pm. Tell me how to do it?
here I am accessing the key 'mon'
String dateFormat = DateFormat('EEE').format(timeNow).toLowerCase();
shopSchedule.templateFull![dateFormat]
You can do this to get closest time after now from your mon list:
String? selectedTime;
for (var element in mon) {
if (selectedTime == null) {
var now = DateTime.now();
DateTime tempDate = DateFormat("yyyy-MM-dd hh:mm").parse(
"${now.year}-${now.month}-${now.day} ${element["start_time"] as String}");
if (tempDate.isAfter(now)) {
selectedTime = element["start_time"];
}
} else {
var now = DateTime.now();
DateTime selectedDate = DateFormat("yyyy-MM-dd hh:mm")
.parse("${now.year}-${now.month}-${now.day} $selectedTime");
DateTime tempDate = DateFormat("yyyy-MM-dd hh:mm").parse(
"${now.year}-${now.month}-${now.day} ${element["start_time"] as String}");
if (tempDate.isBefore(selectedDate) && tempDate.isAfter(now)) {
selectedTime = element["start_time"];
}
}
}

Save the differences between two dates in list flutter

I want to store the dates between two dates in list for example if the
start date = 3/4/2021 and the end date = 7/4/2021
then the list items are [3/4/2021,4/4/2021,5/4/2021,6/4/2021,7/4/2021]
DateTime medStartDate =
doc[index]['medicationStartDate'].toDate();
DateTime medEndDate = doc[index]['medicationEndDate'].toDate();
final difference = medEndDate.difference(medStartDate).inDays;
but how to save the dates ?
You can iterate over a range like this:
void main() {
final startDate = DateTime.now();
final endDate = startDate.add(Duration(days: 5));
final interval = calculateInterval(startDate, endDate);
print(interval);
}
List<DateTime> calculateInterval(DateTime startDate, DateTime endDate) {
List<DateTime> days = [];
for (int i = 0; i <= endDate.difference(startDate).inDays; i++) {
days.add(startDate.add(Duration(days: i)));
}
return days;
}
And the result:
[2021-04-07 16:27:15.480, 2021-04-08 16:27:15.480, 2021-04-09 16:27:15.480, 2021-04-10 16:27:15.480, 2021-04-11 16:27:15.480, 2021-04-12 16:27:15.480]

How to determine which DateTime is greater or less than the other

How it should work:
Make sure that today is between 2020-April-01(timestampValidFrom - firebase timestamp format) and 2020-April-05(timestampValidTo).
I need like this query.
1)
timestampValidFrom <= today >= timestampValidTo
or
2)
.where('timestampValidFrom', isGreaterThanOrEqualTo: Timestamp.now())
.where('timestampValidTo', isLessThanOrEqualTo: Timestamp.now())
I have tried to fix this solution, but it does not work.
DateTime now = DateTime.now();
DateTime yesterday,tomorrow;
yesterday = DateTime(now.year, now.month, now.day); // today 12.00.00
tomorrow = DateTime(now.year, now.month, now.day +1); //tomorrow 12.00.00
if(yesterday.isAfter(snapshot.data[index].timestampValidFrom.toDate())
|| snapshot.data[index].timestampValidFrom.toDate().isBefore(tomorrow)
&& yesterday.isBefore(snapshot.data[index].timestampValidTo.toDate())
|| snapshot.data[index].timestampValidTo.toDate().isAfter(tomorrow)) {
// show widget
} else {
//emplty widget
}
you can use DateTime.compareTo to perform greater-than-or-equal-to or less-than-or-equal-to checks:
var today = DateTime.now();
var isValid = today.compareTo(timestampValidFrom) >= 0 &&
today.compareTo(timeStampValidTo) <= 0;
You can define operator <= and operator >= on DateTime as extensions to make this comparison easier to read. package:basics does this for you:
import 'package:basics/basics.dart';
...
var today = DateTime.now();
var isValid = today >= timestampValidFrom && today <= timestampValidTo;
Use the difference method.
final yesterday = DateTime(now.year, now.month, now.day); // today 12.00.00
final tomorrow = DateTime(now.year, now.month, now.day +1); //tomorrow 12.00.00
int diffInDays = tomorrow.difference(yesterday).inDays;
if (diffInDays == 0){
//custom code
print( "same day");
} else if( diffInDays > 0 ) {
// custom code
print("tomorrow is greater ");
} else{
// custom code
print(" yesterday is less" );
}
Hope it helps!
You can simply check whether the current date is between the promotion start date and end date, if yes show the promotion else hide it.
DateTime now = DateTime.now();
DateTime beg = snapshot.data[index].timestampValidFrom.toDate();
DateTime end = snapshot.data[index].timestampValidTo.toDate();
if(now.isAfter(beg) && now.isBefore(end)){
print('show promo');
} else{
print('remove promo');
}
It won't include the start & end date. For including the start date, check the following if statement:
if((now.difference(beg).inMinutes >= 0 || now.isAfter(beg)) && (now.isBefore(end) || now.difference(end).inMinutes <= 0)){
print('show promo');
}else{
print('remove promo');
}

convent and find The difference between date time flutter

I need to help with my fluter code,
I have an API its response me a date as a String
{"time": "12/04/2020 16:09:33"}
and I get the current time in my code from the phone using
var now = new DateTime.now();
how I can calculate the difference between two date-time???
You can use the intl library.
import 'package:intl/intl.dart';
String formatDuration(Duration duration) {
return duration.toString().split('.').first.padLeft(8, '0');
}
final s = "12/04/2020 16:09:33";
final formatter = DateFormat('dd/MM/yyyy HH:mm:ss');
final dateTime = formatter.parse(s);
var now = DateTime.now();
var difference = now.difference(dateTime);
print(formatDuration(difference));
print result ex. 53:37:11
You can achieve that using difference() method which accepts date as DateTime object. Hence, first you need to convert your input date which is in String format, into DateTime. Working code below:
String date = "12/04/2020 16:09:33";
DateFormat dateFormat = DateFormat("yyyy/MM/dd HH:mm:ss");
DateTime dateTime = dateFormat.parse(date); // converts into Datetime
var nowDate = DateTime.now();
var difference = nowDate.difference(dateTime);
print(difference); // 17553602:53:49.047936

Add/Subtract months/years to date in dart?

I saw that in dart there is a class Duration but it cant be used add/subtract years or month. How did you managed this issue, I need to subtract 6 months from an date. Is there something like moment.js for dart or something around?
Thank you
Okay so you can do that in two steps, taken from #zoechi (a big contributor to Flutter):
Define the base time, let us say:
var date = new DateTime(2018, 1, 13);
Now, you want the new date:
var newDate = new DateTime(date.year, date.month - 1, date.day);
And you will get
2017-12-13
You can use the subtract and add methods
date1.subtract(Duration(days: 7, hours: 3, minutes: 43, seconds: 56));
date1.add(Duration(days: 1, hours: 23)));
Flutter Docs:
Subtract
Add
Try out this package, Jiffy. Adds and subtracts date time with respect to how many days there are in a month and also leap years. It follows the simple syntax of momentjs
You can add and subtract using the following units
years, months, weeks, days, hours, minutes, seconds and milliseconds
To add 6 months
DateTime d = Jiffy().add(months: 6).dateTime; // 2020-04-26 10:05:57.469367
// You can also add you own Datetime object
DateTime d = Jiffy(DateTime(2018, 1, 13)).add(months: 6).dateTime; // 2018-07-13 00:00:00.000
You can also do chaining using dart method cascading
var jiffy = Jiffy().add(months: 5, years: 1);
DateTime d = jiffy.dateTime; // 2021-03-26 10:07:10.316874
// you can also format with ease
String s = jiffy.format("yyyy, MMM"); // 2021, Mar
// or default formats
String s = jiffy.yMMMMEEEEdjm; // Friday, March 26, 2021 10:08 AM
You can use subtract and add methods
Subtract
Add
But you have to reassign the result to the variable, which means:
This wouldn't work
date1.add(Duration(days: 1, hours: 23)));
But this will:
date1 = date1.add(Duration(days: 1, hours: 23)));
For example:
void main() {
var d = DateTime.utc(2020, 05, 27, 0, 0, 0);
d.add(Duration(days: 1, hours: 23));
// the prev line has no effect on the value of d
print(d); // prints: 2020-05-27 00:00:00.000Z
//But
d = d.add(Duration(days: 1, hours: 23));
print(d); // prints: 2020-05-28 23:00:00.000Z
}
Dartpad link
In simple way without using any lib you can add Month and Year
var date = new DateTime(2021, 1, 29);
Adding Month :-
date = DateTime(date.year, date.month + 1, date.day);
Adding Year :-
date = DateTime(date.year + 1, date.month, date.day);
Not so simple.
final date = DateTime(2017, 1, 1);
final today = date.add(const Duration(days: 1451));
This results in 2020-12-21 23:00:00.000 because Dart considers daylight to calculate dates (so my 1451 days is missing 1 hour, and this is VERY dangerous (for example: Brazil abolished daylight savings in 2019, but if the app was written before that, the result will be forever wrong, same goes if the daylight savings is reintroduced in the future)).
To ignore the dayligh calculations, do this:
final date = DateTime(2017, 1, 1);
final today = DateTime(date.year, date.month, date.day + 1451);
Yep. Day is 1451 and this is OK. The today variable now shows the correct date and time: 2020-12-12 00:00:00.000.
It's pretty straightforward.
Simply add or subtract with numbers on DateTime parameters based on your requirements.
For example -
~ Here I had a requirement of getting the date-time exactly 16 years before today even with milliseconds and in the below way I got my solution.
DateTime today = DateTime.now();
debugPrint("Today's date is: $today"); //Today's date is: 2022-03-17 09:08:33.891843
After desired subtraction;
DateTime desiredDate = DateTime(
today.year - 16,
today.month,
today.day,
today.hour,
today.minute,
today.second,
today.millisecond,
today.microsecond,
);
debugPrint("16 years ago date is: $desiredDate"); // 16 years before date is: 2006-03-17 09:08:33.891843
Increase and Decrease of the day/month/year can be done by DateTime class
Initialise DateFormat which needed to be shown
var _inputFormat = DateFormat('EE, d MMM yyyy');
var _selectedDate = DateTime.now();
Increase Day/month/year:
_selectedDate = DateTime(_selectedDate.year,
_selectedDate.month + 1, _selectedDate.day);
Increase Day/month/year:
_selectedDate = DateTime(_selectedDate.year,
_selectedDate.month - 1, _selectedDate.day);
Above example is for only month, similar way we can increase or decrease year and day.
Can subtract any count of months.
DateTime subtractMonths(int count) {
var y = count ~/ 12;
var m = count - y * 12;
if (m > month) {
y += 1;
m = month - m;
}
return DateTime(year - y, month - m, day);
}
Also works
DateTime(date.year, date.month + (-120), date.day);
Future<void> main() async {
final DateTime now = DateTime.now();
var kdate = KDate.buildWith(now);
log("YEAR", kdate.year);
log("MONTH", kdate.month);
log("DATE", kdate.date);
log("Last Year", kdate.lastYear);
log("Last Month", kdate.lastMonth);
log("Yesturday", kdate.yesturday);
log("Last Week Date", kdate.lastWeekDate);
}
void log(title, data) {
print("\n$title ====> $data");
}
class KDate {
KDate({
this.now,
required this.year,
required this.month,
required this.date,
required this.lastYear,
required this.lastMonth,
required this.yesturday,
required this.lastWeekDate,
});
final DateTime? now;
final String? year;
final String? month;
final String? date;
final String? lastMonth;
final String? lastYear;
final String? yesturday;
final String? lastWeekDate;
factory KDate.buildWith(DateTime now) => KDate(
now: now,
year: (now.year).toString().split(" ")[0],
month: (now.month).toString().split(" ")[0],
date: (now.day).toString().split(" ")[0],
lastYear: (now.year - 1).toString().split(" ")[0],
lastMonth: DateTime(now.year, now.month, now.month)
.subtract(Duration(days: 28))
.toString()
.split(" ")[0]
.toString()
.split("-")[1],
yesturday: DateTime(now.year, now.month, now.day)
.subtract(Duration(days: 1))
.toString()
.split(" ")[0]
.toString()
.split("-")
.last,
lastWeekDate: DateTime(now.year, now.month, now.day)
.subtract(Duration(days: 7))
.toString()
.split(" ")[0]
.toString()
.split("-")
.last,
);
}
I'm a fan of using extensions in dart, and we can use them here like this:
extension DateHelpers on DateTime {
DateTime copyWith({
int? year,
int? month,
int? day,
int? hour,
int? second,
int? millisecond,
int? microsecond,
}) {
return DateTime(
year ?? this.year,
month ?? this.month,
day ?? this.day,
hour ?? this.hour,
second ?? this.second,
millisecond ?? this.millisecond,
microsecond ?? this.microsecond,
);
}
DateTime addYears(int years) {
return copyWith(year: this.year + years);
}
DateTime addMonths(int months) {
return copyWith(month: this.month + months);
}
DateTime addWeeks(int weeks) {
return copyWith(day: this.day + weeks*7);
}
DateTime addDays(int days) {
return copyWith(day: this.day + days);
}
}
You can then use this utility code as follows:
final now = DateTime.now();
final tomorrow = now.addDays(1);
final nextWeek = now.addWeeks(1);
final nextMonth = now.addMonths(1);
final nextYear = now.addYears(1);