显示周数/日历周

时间:2018-10-12 15:19:54

标签: android dart flutter

我希望能够显示当前日历周,但是据我所知,DateTime无法显示。

当前,我必须获取当前日期,将其除以7并四舍五入。最后一部分是我遇到的问题。有没有办法在Flutter中舍入整数?

这是我使用的代码:

class CurrentWeek extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return new CurrentWeekState();
  }
}

class CurrentWeekState extends State<CurrentWeek> {

  DateTime currentTime;
  String currentDayCount;

  @override
  void initState() {
    super.initState();
    currentTime = DateTime.now();
  }


  @override
  Widget build(BuildContext context) {
    currentDayCount = DateFormat("D").format(currentTime);
    return Text(currentDayCount);
  }
}

2 个答案:

答案 0 :(得分:0)

https://pub.dev/packages/week_of_year通过仅在DateTime对象上调用来实现此目的:

如文档中所述:

import 'package:week_of_year/week_of_year.dart';

void main() {
  final date = DateTime.now();
  print(date.weekOfYear); // Get the iso week of year
}

答案 1 :(得分:0)

    getWeekNumber(date) {
  let oneDayMillSeconds = 24 * 60 * 60 * 1000;
  let firstDate = new Date(date);
  firstDate.setMonth(0);
  firstDate.setDate(1);
  firstDate.setHours(0, 0, 0, 0);

  let days = (date.valueOf() - firstDate.valueOf()) / oneDayMillSeconds + 1;
  let yearFirstDay = firstDate.getDay() || 7;
  let week = null;

  if (yearFirstDay === 7) {
      week = Math.ceil(days / yearFirstDay);
  } else {
      days -= (7 - yearFirstDay + 1);
      week = Math.ceil(days / 7) + 1;
  }

  return week;
}