如何在颤振列表中获取给定月份的所有日期?

hou*_*uba 2 date dart flutter

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

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

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

List myListOfDates = Dates(may2020).format(day.month.year)
Run Code Online (Sandbox Code Playgroud)

我怎样才能生产这个?

谢谢

Alo*_*lok 5

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

算法

  1. 输入月份数字和年份,并将其传递到 DateTime()
  2. 查找提供的月份的总天数
  3. 生成所有日期,直到我们从 STEP 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;
}
Run Code Online (Sandbox Code Playgroud)

输出

// 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]
Run Code Online (Sandbox Code Playgroud)

改进

如果要以这种格式存储数据,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);
Run Code Online (Sandbox Code Playgroud)

你也可以,以你喜欢的任何形式存储数据,我喜欢 date/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;
}
Run Code Online (Sandbox Code Playgroud)