gpt4 book ai didi

date - 如何在 flutter 列表中获取给定月份的所有日期?

转载 作者:行者123 更新时间:2023-12-03 04:20:12 30 4
gpt4 key购买 nike

我想知道如何将给定月份和年份的所有日期添加到动态列表中?

这个想法是在数据表中显示这些信息。

如何将所有日期(给定月份)放入列表中?

List myListOfDates = Dates(may2020).format(day.month.year)

我怎样才能制作这个?

谢谢

最佳答案

如果我理解你的情况,我规定的是查找特定指定月份的所有日期。

算法

  1. 获取月份和年份的输入,并将其传递到 DateTime() 中
  2. 找出所提供月份的总天数
  3. 生成所有日期,直到我们从第 1 步获得的总天数
  4. 打印检查

在我们继续代码之前,您可能需要检查一下,这将帮助您更好、更清楚地了解情况:

代码:它不需要任何导入,所以请继续。

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 - 如何在 flutter 列表中获取给定月份的所有日期?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63058039/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com