Skip to main content
Source: AL0026AvoidDateTimeNowAnalyzer.cs

Description

DateTime.Now and DateTime.UtcNow make code difficult to test. Use TimeProvider.System.GetLocalNow() or GetUtcNow() instead, which can be mocked in tests.

Bad Code

Good Code

Properties

  • Category: Usage
  • Severity: Warning
  • Enabled by default: True
  • Code fix available: False

Configuration

Notes

TimeProvider was introduced in .NET 8 and provides a testable abstraction for time-related operations. You can inject a custom TimeProvider in tests to control time behavior.