How to format date in list? - flutter

Is it possible to format a list of dates? I tried formatting it by formatting the list but got an error..
The argument type 'List' can't be assigned to the parameter type 'DateTime'.
var list = <DateTime>[];
DateTime start = DateTime(2018, 12, 30);
final end = DateTime(2022, 12, 31);
while (start.isBefore(end)) {
list.add(start);
start = start.add(const Duration(days: 1));
}
print(DateFormat("MM-dd-yyyy").format(list)); // The argument type 'List<DateTime>' can't be assigned to the parameter type 'DateTime'.
When I format the date before it's put in a list an error comes up saying you can't use isBefore on a string.
var list = <DateTime>[];
DateTime start = DateTime(2018, 12, 30);
var date = DateFormat("MM-dd-yyyy").format(start);
final end = DateTime(2022, 12, 31);
while (date.isBefore(end)) { //The method 'isBefore' isn't defined for the class 'String'.
list.add(start);
start = start.add(const Duration(days: 1));
}

Change the first code snippet to the following code:
var list = <String>[];
DateTime start = DateTime(2018, 12, 30);
final end = DateTime(2022, 12, 31);
while (start.isBefore(end)) {
var formatedData = DateFormat("MM-dd-yyyy").format(start)
list.add(formatedData);
start = start.add(const Duration(days: 1));
}
Since format() method returns a String then change the list to type String and then inside the while loop, you can format the start date and add it to the list.

Related

Convert String With Time in it to int

I get the time of production into a String like time = "16:08". Format:"MM:SS", I need to convert it to int GETTING the seconds to add time on it and let it keep going.
You can do the following steps:
String time = "16:08";
String myHour = time.substring(0, 2); // parse your string
String myMin = time.substring(2, 4); // parse your string
TimeOfDay thisTime = TimeOfDay(hour: int.parse(myHour), minute: int.parse(myMin)); // convert to TimeOfDay
TimeOfDay newTime = thisTime.replacing(hour: thisTime.hour - 2, minute: thisTime.minute + 2); // replace hour and minute
EDIT:
Ok, you can use the Duration class like this:
String time = "16:08";
String myMin = time.substring(0, 2);
String mySec = time.substring(2, 4);
Duration duration = Duration(minutes: int.parse(myMin) + 2, seconds: int.parse(mySec));

How to check if current date and time falls between two given date and time in Flutter

I have the below info:
final startDateTime = DateTime(2020, 7, 6, 18, 00);
final endDateTime = DateTime(2020, 7, 7, 19, 00);
final currentDateTime = DateTime.now();
How do I find if currentDateTime is between startDateTime and endDateTime.
Define a method:
bool isCurrentDateInRange(DateTime startDate, DateTime endDate) {
final currentDate = DateTime.now();
return currentDate.isAfter(startDate) && currentDate.isBefore(endDate);
}
Use it like:
var isDateInRange = isCurrentDateInRange(startDate, endDate);
if (currentDateTime.isAfter(startDateTime) && currentDateTime.isBefore(endDateTime)) {
...
}

Converting a List of DateTime into Strings

I'm trying to covert a list of dates into a string
var list = <DateTime>[];
DateTime start = DateTime(2019, 12, 01);
final end = DateTime(2021, 12, 31);
while (start.isBefore(end)) {
list.add(start);
start = start.add(const Duration(days: 1));
}
list.map((DateTime time) {
var dateRange = DateFormat("MM-dd-yy").format(time);
List<String> userSearchItems = [];
userSearchItems.add(dateRange);
print(userSearchItems);
});
but userSearchItems is coming up as empty
The code block inside list.map is never executed.
This is because list.map produces a lazy transformation of the list. The transformation function is executed only when elements are requested from it.
You probably want to use:
var dates = list.map((DateTime time) {
var dateRange = DateFormat("MM-dd-yy").format(time);
return dateRange;
});
print(dates);
In the code above, it is the print function that forces the transformation to run.
Alternatively, you can transform the result of the list.map to a list using
var datesList = dates.toList();
Again, this forces eager evaluation of the map transformation.

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

Flutter how to get all the days of the week as string in the users locale

AS stated in the title: Is there an easy way to get all the days of the week as string(within a list ofcourse) in the users locale?
My suggestion is:
static List<String> getDaysOfWeek([String locale]) {
final now = DateTime.now();
final firstDayOfWeek = now.subtract(Duration(days: now.weekday - 1));
return List.generate(7, (index) => index)
.map((value) => DateFormat(DateFormat.WEEKDAY, locale)
.format(firstDayOfWeek.add(Duration(days: value))))
.toList();
}
The idea is we define the date of the first day in the current week depending on current week day. Then just do loop 7 times starting from calculated date, add 1 day on each iteration and collect the result of DateFormat().format method with pattern DateFormat.WEEKDAY. To increase performance you can use lazy initialization. For example:
/// Returns a list of week days
static List<String> _daysOfWeek;
static List<String> get daysOfWeek {
if (_daysOfWeek == null) {
_daysOfWeek = getDaysOfWeek(); // Here you can specify your locale
}
return _daysOfWeek;
}
Using the intl package, the easiest way I found would be:
import 'package:intl/intl.dart';
var days = DateFormat.EEEE(Platform.localeName).dateSymbols.STANDALONEWEEKDAYS;
print(days) // => ["Sunday", "Monday", ..., "Saturday"]
You can replace STANDALONEWEEKDAYS with WEEKDAYS to get the names as they would appear within a sentence (e.g. first letter lowercase in some languages).
Also, you may use SHORTWEEKDAYS and STANDALONESHORTWEEKDAYS respectively to get the weekday abbreviations. For even shorter abbreviations, use NARROWWEEKDAYS or STANDALONENARROWWEEKDAYS.
After doing:
import 'package:intl/date_symbol_data_local.dart';
String localeName = "pt_BR"; // "en_US" etc.
initializeDateFormatting(localeName);
Use this:
static List<String> weekDays(String localeName) {
DateFormat formatter = DateFormat(DateFormat.WEEKDAY, localeName);
return [DateTime(2000, 1, 3, 1), DateTime(2000, 1, 4, 1), DateTime(2000, 1, 5, 1),
DateTime(2000, 1, 6, 1), DateTime(2000, 1, 7, 1), DateTime(2000, 1, 8, 1),
DateTime(2000, 1, 9, 1)].map((day) => formatter.format(day)).toList();
}
I'm not sure it qualifies as "easy". Maybe someone here can come up with a better answer.
In case you need the current day or month localized with your phone settings
import 'dart:io';
import 'package:intl/date_symbol_data_local.dart';
final String defaultLocale = Platform.localeName; // Phone local
// String defaultLocale = "pt_BR"; // "en_US" etc. you can define yours as well
// add to init
#override
void initState() {
super.initState();
initializeDateFormatting(defaultLocale);
}
static String _getLocalizedWeekDay(String local, DateTime date) {
final formatter = DateFormat(DateFormat.WEEKDAY, local);
return formatter.format(date);
}
static String _getLocalizedMonth(String local, DateTime date) {
final formatter = DateFormat(DateFormat.MONTH, local);
return formatter.format(date);
}