How to calculate days between dates from JSON - flutter

I get information in a JSON and I'm parsing that to my app.
The date is a string, so I know I need to calculate that in string.
final s = all[index].lastdate; <-- This is where my problem is, i cant access the json from this.
final formatter = DateFormat('yyyy-MM-dd');
final dateTime = formatter.parse(s);
final now = DateTime.now();
final difference = now.difference(dateTime).inDays;
final days ;
if (difference == 0) {
final days = "New";
} else if (difference == 1) {
final days = (difference.toString() + " day");
} else {
final days = (difference.toString() + " days");
}

Related

show data according to number of weeks

i have this ui what i want to achieve is that i want to show data according to the date and also if the number of week is selected 1 then i want to show that same data for seven days from that particular date and after that date i want to remove that item
void chooseDay(CalendarDayModel clickedDay) {
setState(() {
_lastChooseDay = _daysList.indexOf(clickedDay);
for (var day in _daysList) {
day.isChecked = false;
}
CalendarDayModel chooseDay = _daysList[_daysList.indexOf(clickedDay)];
chooseDay.isChecked = true;
dailyPills.clear();
for (var pill in allListOfPills) {
DateTime pillDate =
DateTime.fromMicrosecondsSinceEpoch(pill.time! * 1000);
int? week = pill.howManyWeeks;
int totalDays = week! * 7;
final extraDuration = Duration(days: totalDays);
final startDate = pillDate;
final newDateTime = startDate.add(extraDuration);
if (chooseDay.dayNumber == pillDate.day &&
chooseDay.month == pillDate.month &&
chooseDay.year == pillDate.year) {
log("first condition vhitra");
dailyPills.add(pill);
} else if (pillDate.day + 7 != newDateTime.day + 1) {
dailyPills.add(pill);
} else if (newDateTime.day.isLowerThan(chooseDay.dayNumber!)) {
setState(() {
dailyPills.clear();
});
}
}
dailyPills.sort((pill1, pill2) => pill1.time!.compareTo(pill2.time!));
});
}
this is what i tried need some insight here thanks

flutter:: Is it possible to change the timezone of a datetime?

I want to represent the time the file was saved as a string. The time in my country is 9 hours ahead of utc time. How can I change the current utc time to 9 hours faster?
String _getTime({required String filePath}) {
String fromPath = filePath.substring(
filePath.lastIndexOf('/') + 1, filePath.lastIndexOf('.'));
if (fromPath.startsWith("1", 0)) {
DateTime dateTime =
DateTime.fromMillisecondsSinceEpoch(int.parse(fromPath));
var dateLocal = dateTime.toLocal();
print(dateLocal);
print(dateTime);
int year = dateLocal.year;
int month = dateLocal.month;
int day = dateLocal.day;
int hour = dateLocal.hour;
int min = dateLocal.minute;
String dato = '$year-$month-$day--$hour:$min';
return dato;
} else {
return "No Date";
}
}
Use this package ---->>>>> https://pub.dev/packages/flutter_native_timezone
Add the package dependencies to your project, import the package into the file you're working in and write the code below to get your currenTimeZone
final String currentTimeZone = await FlutterNativeTimezone.getLocalTimezone();
debugPrint(currentTimeZone);

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]

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)

How to display time ago like Youtube in Flutter

I'm writing a flutter app to clone some Youtube functionalities using Youtube API V3.
The app fetches video timestamp as a String from youtube video API
Each timestamp has this format :
YYYY-MM-DDTHH:MM:SSZ
One example would be:
2020-07-12T20:42:19Z
I would like to display in a text :
1 hour
1 hours ago
4 weeks ago
11 months ago
1 year ago
...
I've created an extension on String
extension StringExtension on String {
static String displayTimeAgoFromTimestamp(String timestamp) {
final year = int.parse(timestamp.substring(0, 4));
final month = int.parse(timestamp.substring(5, 7));
final day = int.parse(timestamp.substring(8, 10));
final hour = int.parse(timestamp.substring(11, 13));
final minute = int.parse(timestamp.substring(14, 16));
final DateTime videoDate = DateTime(year, month, day, hour, minute);
final int diffInHours = DateTime.now().difference(videoDate).inHours;
String timeAgo = '';
String timeUnit = '';
int timeValue = 0;
if (diffInHours < 1) {
final diffInMinutes = DateTime.now().difference(videoDate).inMinutes;
timeValue = diffInMinutes;
timeUnit = 'minute';
} else if (diffInHours < 24) {
timeValue = diffInHours;
timeUnit = 'hour';
} else if (diffInHours >= 24 && diffInHours < 24 * 7) {
timeValue = (diffInHours / 24).floor();
timeUnit = 'day';
} else if (diffInHours >= 24 * 7 && diffInHours < 24 * 30) {
timeValue = (diffInHours / (24 * 7)).floor();
timeUnit = 'week';
} else if (diffInHours >= 24 * 30 && diffInHours < 24 * 12 * 30) {
timeValue = (diffInHours / (24 * 30)).floor();
timeUnit = 'month';
} else {
timeValue = (diffInHours / (24 * 365)).floor();
timeUnit = 'year';
}
timeAgo = timeValue.toString() + ' ' + timeUnit;
timeAgo += timeValue > 1 ? 's' : '';
return timeAgo + ' ago';
}
}
Then call in text:
StringExtension.displayTimeAgoFromTimestamp(video.timestamp)
You can use the timeago package
example code below
import 'package:timeago/timeago.dart' as timeago;
main() {
final fifteenAgo = new DateTime.now().subtract(new Duration(minutes: 15));
print(timeago.format(fifteenAgo)); // 15 minutes ago
print(timeago.format(fifteenAgo, locale: 'en_short')); // 15m
print(timeago.format(fifteenAgo, locale: 'es')); // hace 15 minutos
}
to use it with the YYYY-MM-DDTHH:MM:SSZ time format you can convert the String to a DateTime then perform the operation on the DateTime variable
DateTime time = DateTime.parse("2020-07-12T20:42:19Z");
print(timeago.format(time));
I've created reusable function for sample, this might be helpful!!
import 'package:intl/intl.dart';
//for DateTime manipulation need to add this package
import 'package:timeago/timeago.dart' as timeago;
void main(){
//creating this getTimeAgo function to format dateTime with user inputs
dynamic getTimeAgo(DateTime d) {
dynamic value = "";
//setting current time variable now
final now = DateTime.now();
//converting the user provided date to LocalTime
final recvDate = d.toLocal();
//declaring today's date in today variable
final today = DateTime(now.year, now.month, now.day);
//declaring yesterday's date in yesterday variable
final yesterday = DateTime(now.year, now.month, now.day - 1);
//declaring user provided date's in date variable
final date = DateTime(recvDate.year, recvDate.month, recvDate.day);
//comparing today's date is equal to user provided date then return value with timeAgo flutter package response
if (date == today) {
final curtimeNow = timeago.format(d);
if (curtimeNow == 'a day ago') {
value = "1 day ago";
} else if (curtimeNow == 'about an hour ago') {
value = "1 hour ago";
} else {
value = curtimeNow;
}
} //comparing yesterday's date is equal to user provided date then return 1 day ago
else if (date == yesterday) {
value='1 day ago';
} //else the user provided date then return as the date format of dd MMM yyyy Eg. 10 Mar 2022
else {
value = DateFormat('dd MMM yyyy').format(date);
}
//returning the response
return value;
}
//declaring the date which is to used be formatted
var recvdDateTime=DateTime.now().subtract(Duration(minutes: 45));;
//calling the getTimeAgo (fn) with user input
getTimeAgo(DateTime.parse(recvdDateTime));
}