> ## Content Index
> Fetch the complete content index at: https://www.markrsh.com/llms.txt
> Use this file to discover other available public pages before exploring further.

# Testing Time-Dependent Dart Code With package:clock
- URL: https://www.markrsh.com/grappling-with-dates-in-dart/
- Published: 2025-03-01T16:20:00.000Z
- Updated: 2026-08-31T09:59:41.000Z
- Description: If you've ever wondered how to test Dart methods with dates, there is a simple solution that the Dart team use.
- Author: Mark Houghton

If you've ever tried testing Dart methods with internal dates, you may have noticed it can quickly become painful.

Let's consider the following method with an internal dependency on the current time.

```dart
void methodWithInternalDate() {
  final today = DateTime.now();

  // logic dependent on the current time
}

```

If we need to assume the method has a fixed time as part of our testing, then the standard approach would be to inject the required date into the method as an argument. This gets quite messy, either making it `nullable` and only using it for testing, which feels like a hack

```dart
  void someMethodWithDate(DateTime? time) {
    final today = time ?? DateTime.now();

    // code that uses today
  }

```

or requiring the argument, but then we generate extra bloat whenever calling the method outside of tests

```dart
  void someMethodWithDate(DateTime time) {
    final today = time;

    // code that uses today
  }

```

Neither seem ideal, so we can use the [clock package](https://pub.dev/packages/clock?ref=markrsh.com) developed by the Dart team instead.

```dart
  import 'package:clock/clock.dart';

  void someMethodWithDate() {
    final today = clock.now();

    // code that uses today
  }

```

With this in place, we can easily fix dates as needed when writing tests

```dart
  test('some unit test that requires fixed time', () {
    // set up
    final date = DateTime.now();
    final dummyTime = DateTime(date.year, date.month, date.day, 15, 0, 0);

    final result = withClock(
      Clock.fixed(dummyTime),
      () => someClass.someMethodWithDate(),
    );
  });

```