【发布时间】:2020-07-23 15:40:52
【问题描述】:
我想知道如何将给定月份和年份的所有日期添加到动态列表中?
这个想法是在数据表中显示这些信息。
如何将所有日期(给定月份)放入列表中?
List myListOfDates = Dates(may2020).format(day.month.year)
我怎样才能制作这个?
谢谢
【问题讨论】:
我想知道如何将给定月份和年份的所有日期添加到动态列表中?
这个想法是在数据表中显示这些信息。
如何将所有日期(给定月份)放入列表中?
List myListOfDates = Dates(may2020).format(day.month.year)
我怎样才能制作这个?
谢谢
【问题讨论】:
如果我理解你的情况,我的规定是查找特定月份的所有日期。
算法
在我们继续代码之前,您可能需要检查一下,这将有助于您更好地了解情况:
代码:它不需要任何导入,所以请继续。
void main() {
// Take the input year, month number, and pass it inside DateTime()
var now = DateTime(2020, 7);
// Getting the total number of days of the month
var totalDays = daysInMonth(now);
// Stroing all the dates till the last date
// since we have found the last date using generate
var listOfDates = new List<int>.generate(totalDays, (i) => i + 1);
print(listOfDates);
}
// this returns the last date of the month using DateTime
int daysInMonth(DateTime date){
var firstDayThisMonth = new DateTime(date.year, date.month, date.day);
var firstDayNextMonth = new DateTime(firstDayThisMonth.year, firstDayThisMonth.month + 1, firstDayThisMonth.day);
return firstDayNextMonth.difference(firstDayThisMonth).inDays;
}
输出
// since we used month 7, in the DateTime(), so it returned 31, which will give output
// till last date of the specified month
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31]
改进
如果您想以这种格式存储数据,dd/mm/yyyy。我们总是可以修改它。可以这样做,对代码稍作改进
// make sure you define you List<String> not List<int> in the previous code
// also, in place of May and 2020, you can add your input params for month and year, make sure to convert the numeric month to word format like 7 => July
// like "${i+1} $month, $year"
// I have used my words only
var listOfDates = new List<String>.generate(lastDateOfMonth, (i) => "${i+1}/July/2020");
print(listOfDates);
你也可以,以任何你喜欢的形式存储数据,我喜欢date/month/year
输出
[1/July/2020, 2/July/2020, 3/July/2020, 4/July/2020, 5/July/2020, 6/July/2020, 7/July/2020, 8/July/2020, 9/July/2020, 10/July/2020, 11/July/2020, 12/July/2020, 13/July/2020, 14/July/2020, 15/July/2020, 16/July/2020, 17/July/2020, 18/July/2020, 19/July/2020, 20/July/2020, 21/July/2020, 22/July/2020, 23/July/2020, 24/July/2020, 25/July/2020, 26/July/2020, 27/July/2020, 28/July/2020, 29/July/2020, 30/July/2020, 31/July/2020]
【讨论】:
首先,我们需要这个date_util 包来获取一个月的天数。
其次,我们将需要这个intl 包来获取日期时间格式。
你可以通过下面的代码试试:
导入'package:date_util/date_util.dart';
导入'package:intl/intl.dart';
@override
void initState() {
final daysCount = DateUtil().daysInMonth(DateTime.may, 2020);
List<String> days = [];
for (int i = 1; i < daysCount+1; i++) {
days.add(DateFormat(DateFormat.YEAR_MONTH_DAY)
.format(DateTime(2020, DateTime.may, i)));
}
super.initState();
}
您可以将 DateFormat.YEAR_MONTH_DAY 更改为您需要的任何内容
这是输出的图像
【讨论】: