Flutter: Check if date is between two dates - flutter

I need to check date is between two dates or not.
I tried to search it but didn't got fruitful results.
May be you have seen such scenarios. So, seeking your advise.
Here is my code.
var service_start_date = '2020-10-17';
var service_end_date = '2020-10-23';
var service_start_time = '10:00:00';
var service_end_time = '11:00:00';
DateTime currentDate = new DateTime.now();
DateTime times = DateTime.now();
#override
void initState() {
super.initState();
test();
}
test() {
String currenttime = DateFormat('HH:mm').format(times);
String currentdate = DateFormat('yyyy-mm-dd').format(currentDate);
print(currenttime);
print(currentdate);
}
So, basically i have start date and end date. I need to check current date is falling between these two dates or not.

You can check before/after using 'isBefore' and 'isAfter' in 'DateTime' class.
DateTime startDate = DateTime.parse(service_start_date);
DateTime endDate = DateTime.parse(service_end_date);
DateTime now = DateTime.now();
print('now: $now');
print('startDate: $startDate');
print('endDate: $endDate');
print(startDate.isBefore(now));
print(endDate.isAfter(now));

I've made a series of extensions
extension DateTimeExtension on DateTime? {
bool? isAfterOrEqualTo(DateTime dateTime) {
final date = this;
if (date != null) {
final isAtSameMomentAs = dateTime.isAtSameMomentAs(date);
return isAtSameMomentAs | date.isAfter(dateTime);
}
return null;
}
bool? isBeforeOrEqualTo(DateTime dateTime) {
final date = this;
if (date != null) {
final isAtSameMomentAs = dateTime.isAtSameMomentAs(date);
return isAtSameMomentAs | date.isBefore(dateTime);
}
return null;
}
bool? isBetween(
DateTime fromDateTime,
DateTime toDateTime,
) {
final date = this;
if (date != null) {
final isAfter = date.isAfterOrEqualTo(fromDateTime) ?? false;
final isBefore = date.isBeforeOrEqualTo(toDateTime) ?? false;
return isAfter && isBefore;
}
return null;
}
}
I'm hoping they're self explanatory but obviously you can call them like
DateTime.now().isBefore(yourDate)
DateTime.now().isAfter(yourDate)
DateTime.now().isBetween(fromDate, toDate)

Don't forget to check if the day is the same as the one of the two dates also
by adding an or to the condition ex:
if ( start is before now || (start.month==now.month && start.day==now.day ...etc)

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"];
}
}
}

How can I add working days to a specific date (Flutter)?

I want to add the calulated working days to a specific date.
For example
I want to add 14 working days
date -> 08.17.2022 (it is input)
newDate -> 09.06.20222 (it is output)
I tried it with the code below but it didn't work as I want. What is my wrong? How can I do that?
Thanks in advance.
final workingDays = <DateTime>[];
final currentDate = DateTime.fromMicrosecondsSinceEpoch(
widget.siparisModel.siparisTarih.microsecondsSinceEpoch);
final orderDate = currentDate.add(Duration(days: 15));
DateTime indexDate = currentDate;
while (indexDate.difference(orderDate).inDays != 0) {
final isWeekendDay = indexDate.weekday == DateTime.saturday || indexDate.weekday == DateTime.sunday;
if (!isWeekendDay) {
workingDays.add(indexDate);
}
indexDate = indexDate.add(Duration(days: 15));
}
You could do something like this:
var newDate = DateTime(2022, 08, 17); // Copy from some "currentDate"
var numOfWeekdaysToAdd = 14;
while (numOfWeekdaysToAdd > 0) {
do {
newDate = newDate.add(Duration(days: 1));
} while (newDate.weekday == DateTime.saturday || newDate.weekday == DateTime.sunday);
numOfWeekdaysToAdd--;
}
Working DartPad demo:
https://dartpad.dev/?id=6ef6f4306944b350edfb77905239297e
If you want to, you could extend the "weekend-check" and make it more complex to also check for holidays in a specific locale. In that case I'd have a list of holiday-dates, and just add something like holidayDates.contains(newDate)

how to get difference(remaining time ) between '22:00:00' & '00:22:00' in flutter [duplicate]

I'm working on a flutter app as a project and I'm stuck with how to get the difference between two times. The first one I'm getting is from firebase as a String, which I then format to a DateTime using this:DateTime.parse(snapshot.documents[i].data['from']) and it gives me 14:00 for example. Then, the second is DateTime.now().
I tried all methods difference, subtract, but nothing works!
Please help me to get the exact duration between those 2 times.
I need this for a Count Down Timer.
This is an overview of my code:
.......
class _ActualPositionState extends State<ActualPosition>
with TickerProviderStateMixin {
AnimationController controller;
bool hide = true;
var doc;
String get timerString {
Duration duration = controller.duration * controller.value;
return '${duration.inHours}:${duration.inMinutes % 60}:${(duration.inSeconds % 60).toString().padLeft(2, '0')}';
}
#override
void initState() {
super.initState();
var d = Firestore.instance
.collection('users')
.document(widget.uid);
d.get().then((d) {
if (d.data['parking']) {
setState(() {
hide = false;
});
Firestore.instance
.collection('historyParks')
.where('idUser', isEqualTo: widget.uid)
.getDocuments()
.then((QuerySnapshot snapshot) {
if (snapshot.documents.length == 1) {
for (var i = 0; i < snapshot.documents.length; i++) {
if (snapshot.documents[i].data['date'] ==
DateFormat('EEE d MMM').format(DateTime.now())) {
setState(() {
doc = snapshot.documents[i].data;
});
Duration t = DateTime.parse(snapshot.documents[i].data['until'])
.difference(DateTime.parse(
DateFormat("H:m:s").format(DateTime.now())));
print(t);
}
}
}
});
}
});
controller = AnimationController(
duration: Duration(hours: 1, seconds: 10),
vsync: this,
);
controller.reverse(from: controller.value == 0.0 ? 1.0 : controller.value);
}
double screenHeight;
#override
Widget build(BuildContext context) {
screenHeight = MediaQuery.of(context).size.height;
return Scaffold(
.............
you can find the difference between to times by using:
DateTime.now().difference(your_start_time_here);
something like this:
var startTime = DateTime(2020, 02, 20, 10, 30); // TODO: change this to your DateTime from firebase
var currentTime = DateTime.now();
var diff = currentTime.difference(startTime).inDays; // HINT: you can use .inDays, inHours, .inMinutes or .inSeconds according to your need.
example from DartPad:
void main() {
final startTime = DateTime(2020, 02, 20, 10, 30);
final currentTime = DateTime.now();
final diff_dy = currentTime.difference(startTime).inDays;
final diff_hr = currentTime.difference(startTime).inHours;
final diff_mn = currentTime.difference(startTime).inMinutes;
final diff_sc = currentTime.difference(startTime).inSeconds;
print(diff_dy);
print(diff_hr);
print(diff_mn);
print(diff_sc);
}
Output: 3,
77,
4639,
278381,
Hope this helped!!
You can use the DateTime class to find out the difference between two dates.
DateTime dateTimeCreatedAt = DateTime.parse('2019-9-11');
DateTime dateTimeNow = DateTime.now();
final differenceInDays = dateTimeNow.difference(dateTimeCreatedAt).inDays;
print('$differenceInDays');
final differenceInMonths = dateTimeNow.difference(dateTimeCreatedAt).inMonths;
print('$differenceInMonths');
Use this code:
var time1 = "14:00";
var time2 = "09:00";
Future<int> getDifference(String time1, String time2) async
{
DateFormat dateFormat = DateFormat("yyyy-MM-dd");
var _date = dateFormat.format(DateTime.now());
DateTime a = DateTime.parse('$_date $time1:00');
DateTime b = DateTime.parse('$_date $time2:00');
print('a $a');
print('b $a');
print("${b.difference(a).inHours}");
print("${b.difference(a).inMinutes}");
print("${b.difference(a).inSeconds}");
return b.difference(a).inHours;
}
To compute a difference between two times, you need two DateTime objects. If you have times without dates, you will need to pick a date. Note that this is important because the difference between two times can depend on the date if you're using a local timezone that observes Daylight Saving Time.
If your goal is to show how long it will be from now to the next specified time in the local timezone:
import 'package:intl/intl.dart';
/// Returns the [Duration] from the current time to the next occurrence of the
/// specified time.
///
/// Always returns a non-negative [Duration].
Duration timeToNext(int hour, int minute, int second) {
var now = DateTime.now();
var nextTime = DateTime(now.year, now.month, now.day, hour, minute, second);
// If the time precedes the current time, treat it as a time for tomorrow.
if (nextTime.isBefore(now)) {
// Note that this is not the same as `nextTime.add(Duration(days: 1))` across
// DST changes.
nextTime = DateTime(now.year, now.month, now.day + 1, hour, minute, second);
}
return nextTime.difference(now);
}
void main() {
var timeString = '14:00';
// Format for a 24-hour time. See the [DateFormat] documentation for other
// format specifiers.
var timeFormat = DateFormat('HH:mm');
// Parsing the time as a UTC time is important in case the specified time
// isn't valid for the local timezone on [DateFormat]'s default date.
var time = timeFormat.parse(timeString, true);
print(timeToNext(time.hour, time.minute, time.second));
}
You can use this approch
getTime(time) {
if (!DateTime.now().difference(time).isNegative) {
if (DateTime.now().difference(time).inMinutes < 1) {
return "a few seconds ago";
} else if (DateTime.now().difference(time).inMinutes < 60) {
return "${DateTime.now().difference(time).inMinutes} minutes ago";
} else if (DateTime.now().difference(time).inMinutes < 1440) {
return "${DateTime.now().difference(time).inHours} hours ago";
} else if (DateTime.now().difference(time).inMinutes > 1440) {
return "${DateTime.now().difference(time).inDays} days ago";
}
}
}
And You can call it getTime(time) Where time is DateTime Object.

Date Comparison in Dart/Flutter

I am trying to compare two DateTimes in flutter and execute a particular function using if statements. However, I have been getting NoSuchMethodError.
Here is my code:
DateTime _myNowTime; DateTime _myClickTime
_getClickTime()async{ FirebaseUser currentUser = await
FirebaseAuth.instance.currentUser();
Firestore.instance.collection('user').document(currentUser.uid).snapshots().listen((event) {
if(event.data.isNotEmpty){ setState(() { _now_time = event['now_time'];
_click_time = event['click_time']; _myNowTime = _now_time.toDate(); _myClickTime = _click_time.toDate();
});
} }); }
I want to create a function:
checkTime(){
if(_myNowTime.compareTo(_myClickTime) >= 30 minutes){
//do something ...}
}
void main() {
var now = DateTime.now();
var yesterday = now.subtract(const Duration(days: 1));
if(now == yesterday) {
print("Dates are the same");
} else print("Dates are not the same");
}

How can I get the difference between 2 times?

I'm working on a flutter app as a project and I'm stuck with how to get the difference between two times. The first one I'm getting is from firebase as a String, which I then format to a DateTime using this:DateTime.parse(snapshot.documents[i].data['from']) and it gives me 14:00 for example. Then, the second is DateTime.now().
I tried all methods difference, subtract, but nothing works!
Please help me to get the exact duration between those 2 times.
I need this for a Count Down Timer.
This is an overview of my code:
.......
class _ActualPositionState extends State<ActualPosition>
with TickerProviderStateMixin {
AnimationController controller;
bool hide = true;
var doc;
String get timerString {
Duration duration = controller.duration * controller.value;
return '${duration.inHours}:${duration.inMinutes % 60}:${(duration.inSeconds % 60).toString().padLeft(2, '0')}';
}
#override
void initState() {
super.initState();
var d = Firestore.instance
.collection('users')
.document(widget.uid);
d.get().then((d) {
if (d.data['parking']) {
setState(() {
hide = false;
});
Firestore.instance
.collection('historyParks')
.where('idUser', isEqualTo: widget.uid)
.getDocuments()
.then((QuerySnapshot snapshot) {
if (snapshot.documents.length == 1) {
for (var i = 0; i < snapshot.documents.length; i++) {
if (snapshot.documents[i].data['date'] ==
DateFormat('EEE d MMM').format(DateTime.now())) {
setState(() {
doc = snapshot.documents[i].data;
});
Duration t = DateTime.parse(snapshot.documents[i].data['until'])
.difference(DateTime.parse(
DateFormat("H:m:s").format(DateTime.now())));
print(t);
}
}
}
});
}
});
controller = AnimationController(
duration: Duration(hours: 1, seconds: 10),
vsync: this,
);
controller.reverse(from: controller.value == 0.0 ? 1.0 : controller.value);
}
double screenHeight;
#override
Widget build(BuildContext context) {
screenHeight = MediaQuery.of(context).size.height;
return Scaffold(
.............
you can find the difference between to times by using:
DateTime.now().difference(your_start_time_here);
something like this:
var startTime = DateTime(2020, 02, 20, 10, 30); // TODO: change this to your DateTime from firebase
var currentTime = DateTime.now();
var diff = currentTime.difference(startTime).inDays; // HINT: you can use .inDays, inHours, .inMinutes or .inSeconds according to your need.
example from DartPad:
void main() {
final startTime = DateTime(2020, 02, 20, 10, 30);
final currentTime = DateTime.now();
final diff_dy = currentTime.difference(startTime).inDays;
final diff_hr = currentTime.difference(startTime).inHours;
final diff_mn = currentTime.difference(startTime).inMinutes;
final diff_sc = currentTime.difference(startTime).inSeconds;
print(diff_dy);
print(diff_hr);
print(diff_mn);
print(diff_sc);
}
Output: 3,
77,
4639,
278381,
Hope this helped!!
You can use the DateTime class to find out the difference between two dates.
DateTime dateTimeCreatedAt = DateTime.parse('2019-9-11');
DateTime dateTimeNow = DateTime.now();
final differenceInDays = dateTimeNow.difference(dateTimeCreatedAt).inDays;
print('$differenceInDays');
final differenceInMonths = dateTimeNow.difference(dateTimeCreatedAt).inMonths;
print('$differenceInMonths');
Use this code:
var time1 = "14:00";
var time2 = "09:00";
Future<int> getDifference(String time1, String time2) async
{
DateFormat dateFormat = DateFormat("yyyy-MM-dd");
var _date = dateFormat.format(DateTime.now());
DateTime a = DateTime.parse('$_date $time1:00');
DateTime b = DateTime.parse('$_date $time2:00');
print('a $a');
print('b $a');
print("${b.difference(a).inHours}");
print("${b.difference(a).inMinutes}");
print("${b.difference(a).inSeconds}");
return b.difference(a).inHours;
}
To compute a difference between two times, you need two DateTime objects. If you have times without dates, you will need to pick a date. Note that this is important because the difference between two times can depend on the date if you're using a local timezone that observes Daylight Saving Time.
If your goal is to show how long it will be from now to the next specified time in the local timezone:
import 'package:intl/intl.dart';
/// Returns the [Duration] from the current time to the next occurrence of the
/// specified time.
///
/// Always returns a non-negative [Duration].
Duration timeToNext(int hour, int minute, int second) {
var now = DateTime.now();
var nextTime = DateTime(now.year, now.month, now.day, hour, minute, second);
// If the time precedes the current time, treat it as a time for tomorrow.
if (nextTime.isBefore(now)) {
// Note that this is not the same as `nextTime.add(Duration(days: 1))` across
// DST changes.
nextTime = DateTime(now.year, now.month, now.day + 1, hour, minute, second);
}
return nextTime.difference(now);
}
void main() {
var timeString = '14:00';
// Format for a 24-hour time. See the [DateFormat] documentation for other
// format specifiers.
var timeFormat = DateFormat('HH:mm');
// Parsing the time as a UTC time is important in case the specified time
// isn't valid for the local timezone on [DateFormat]'s default date.
var time = timeFormat.parse(timeString, true);
print(timeToNext(time.hour, time.minute, time.second));
}
You can use this approch
getTime(time) {
if (!DateTime.now().difference(time).isNegative) {
if (DateTime.now().difference(time).inMinutes < 1) {
return "a few seconds ago";
} else if (DateTime.now().difference(time).inMinutes < 60) {
return "${DateTime.now().difference(time).inMinutes} minutes ago";
} else if (DateTime.now().difference(time).inMinutes < 1440) {
return "${DateTime.now().difference(time).inHours} hours ago";
} else if (DateTime.now().difference(time).inMinutes > 1440) {
return "${DateTime.now().difference(time).inDays} days ago";
}
}
}
And You can call it getTime(time) Where time is DateTime Object.