0

Guys. I want to write a simple code to add X weeks to a chosen Date but I just can't figure out how. I always get a ton of errors. The function should basically return the chosen date plus "addedweeks" in the format "dd-MM-yyyy". Below is my last attempt. Thanks in advance!

import 'dart:math' as math;

String? addXWeeks(
  DateTime? datum,
  int? addedweeks,
) {
  // add 2 weeks 

DateTime date = datum.toLocal;
  date = DateTime(date.year, date.month, date.day + (addedweeks*7));
  
  
}
  • 1. Do you actually want callers to be able to pass `null` arguments to `addXWeeks`? If not, it doesn't make sense for `datum` and `addedweeks` to be nullable. 2. [`DateTime.toLocal`](https://api.dart.dev/stable/dart-core/DateTime/toLocal.html) is a *method* and would need to be invoked: `DateTime date = datum.toLocal();`. Additionally, your comment says "add 2 weeks" but your code adds `addedweeks`, and you discard the time from the original `DateTime` object. – jamesdlin Oct 05 '22 at 14:58

1 Answers1

1

this is very easy. DateTime has a method called add. You only need to add 7 days, because duration has not the propertie "weeks".

Here is a samle:

void main() {
  // Current date
  DateTime date = DateTime.now();
  // Weeks you want to add
  int weeksToAdd = 10;

  print("Before: $date");

  // Multiply 7 (days a week) with your week and set int to and int
  date = date.add(Duration(days: (7 * weeksToAdd).toInt()));

  print("After: $date");

  // Format date
  print("Format date: ${date.day}.${date.month}.${date.year}");
}

The output:

Before: 2022-10-06 13:23:16.342888
After: 2022-12-15 12:23:16.342888
Format date: 15.12.2022
Tom
  • 486
  • 1
  • 2
  • 11
  • Thanks, how do I format it to "dd-MM-yyyy" afterwards? Greeting – OwenGreen Oct 05 '22 at 14:59
  • 1
    One thing to note (and which is demonstrated in your output) is that this code adds weeks as 7 * 24 hour increments, so the time will change across DST events. Also see [Dart Lang: Strange result adding 7 days. Sometimes it doesn't compute well](https://stackoverflow.com/q/68214911/) – jamesdlin Oct 05 '22 at 15:00
  • You can use the package intl from pub.dev to format your date: https://pub.dev/packages/intl, or you write it in a string, I update my code sample for this – Tom Oct 06 '22 at 11:20