3

I want to be able to display the current calendar week, but as far as I have seen that isn't possible with DateTime.

Currently I have to get the current day number, divide it by 7 and round up that number. The last part is where I'm stuck at. Is there a way to round up integers in Flutter?

Here is the code I use:

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);
  }
}
Nagant
  • 31
  • 2

2 Answers2

2

The package: https://pub.dev/packages/week_of_year does exactly this by just calling this on a DateTime Object:

As stated in the documentation:

import 'package:week_of_year/week_of_year.dart';

void main() {
  final date = DateTime.now();
  print(date.weekOfYear); // Get the iso week of year
}
Georgios
  • 861
  • 2
  • 12
  • 30
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;
}
sugar
  • 1