How to implement Upcoming Date Countdown in flutter - flutter

I have a task to implement upcoming event date countdown. Example 1 months 2 days remaining. date is received from api like this 2021-10-18 17:00:00.000Z. I tried some examples but didn't got required output. Below is my implemented code
static String? dateDiff(String date){
if(date != "null") {
final date1 = DateTime.now().toUtc();
final DateTime date2 = DateTime.parse(date).toUtc();
final difference = date2.difference(date1).inDays;
print(difference); //
return difference.toString(); //
}
}

You can check the answer here out
Check here

Related

How do i compare current timestamp to the timestap from firebase flutter

I want to create a function which does not allow the user to remove the appointment once the timestamp for the appointment has past already. But what i tried below does not work, i hope to get some guidance from you guys
My widget.filter is a var which has the timestamp value from firebase
DateTime currentPhoneDate = DateTime.now(); //DateTime
Timestamp myTimeStamp = Timestamp.fromDate(currentPhoneDate); //To TimeStamp
DateTime myDateTime = myTimeStamp.toDate(); // TimeStamp to DateTime
print("current phone data is: $currentPhoneDate");
print("current phone data is: $myDateTime");
if(myTimeStamp < widget.filter){
print('work');
}else{
print('fail');
}
DateTime currentPhoneDate = DateTime.now();
Timestamp myTimeStamp = Timestamp.fromDate(currentPhoneDate);
DateTime myDateTime = myTimeStamp.toDate();
print("myTimeStamp is: $myTimeStamp");
print("currentPhoneDate is: $currentPhoneDate");
print("myDateTime is: $myDateTime");
// if widget.filter DataType is not Timestamp then first convert it to Timestamp.
if (myTimeStamp.millisecondsSinceEpoch <
widget.filter.millisecondsSinceEpoch) {
print('work');
} else {
print('fail');
}

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 to calculate working hours from api data in flutter

i have fetched data from an api which contains employees working time,
i want to calculate total working hours each day
here's how i get the data from the api for 1 single day
Future<List> getPunchData(String empCode, DateTime date) async {
String ip = await confObj.readIp();
DateTime end = new DateTime(date.year, date.month, date.day, 23,59,59);
final response = await http.get(Uri.parse("url/$empCode&$date&$end" ));
final String t = response.body;
var jsonData =jsonDecode(t);
return jsonData;
}
the api result is this:
{
"id": 10,
"punch_time": "2022-03-08 13:30:19.000000",
},
{
"id": 11,
"punch_time": "2022-03-08 16:22:39.000000",
}..
..
..
how can i automatically calculate and isplay total hours when after the widget is loaded
You can use the parse function of the DateTime object to convert the String date into DateTime.
The code would somewhat look like this (can't say for sure as I don't know your API):
final DateTime startTime = DateTime.parse(jsonData[0]['punch_time']);
final DateTime endTime = DateTime.parse(jsonData[1]['punch_time']);
Once you have the DateTime object, you can use the difference function to get a Duration object which will tell you the hours an employee has worked.
final Duration durationWorked = startTime.difference(endTime);
final int hoursWorked = durationWorked.inHours;

Flutter: Check if date is between two dates

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)

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);