DateTime
C#
programming
date comparison
coding tutorial

DateTime.Compare how to check if a date is less than 30 days old?

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

Introduction

In C#, checking if a date is less than 30 days old is simplest with DateTime.Now - date < TimeSpan.FromDays(30) or (DateTime.Now - date).TotalDays < 30. While DateTime.Compare exists for comparing two dates, it only tells you which is earlier — it does not compute a time span. For "less than 30 days old" checks, subtracting dates to get a TimeSpan is the direct and idiomatic approach.

Simple Approach: Subtraction

csharp
1DateTime postDate = new DateTime(2026, 2, 15);
2
3// Subtract to get a TimeSpan
4TimeSpan age = DateTime.Now - postDate;
5
6if (age.TotalDays < 30)
7{
8    Console.WriteLine("Less than 30 days old");
9}
10else
11{
12    Console.WriteLine($"Posted {age.TotalDays:F0} days ago");
13}

Using DateTime.Compare

DateTime.Compare returns -1, 0, or 1 — not a time span. To check "within 30 days", compute the threshold date first:

csharp
1DateTime postDate = new DateTime(2026, 2, 15);
2DateTime thirtyDaysAgo = DateTime.Now.AddDays(-30);
3
4// Compare: is postDate more recent than 30 days ago?
5int result = DateTime.Compare(postDate, thirtyDaysAgo);
6
7if (result > 0)
8{
9    Console.WriteLine("Less than 30 days old");
10}
11else if (result == 0)
12{
13    Console.WriteLine("Exactly 30 days old");
14}
15else
16{
17    Console.WriteLine("More than 30 days old");
18}

Using Comparison Operators (Preferred)

C# DateTime supports <, >, <=, >=, and == directly — no need for DateTime.Compare:

csharp
1DateTime postDate = new DateTime(2026, 2, 15);
2DateTime thirtyDaysAgo = DateTime.Now.AddDays(-30);
3
4// More readable than DateTime.Compare
5if (postDate > thirtyDaysAgo)
6{
7    Console.WriteLine("Less than 30 days old");
8}
9
10// Or check with TimeSpan directly
11if ((DateTime.Now - postDate).TotalDays < 30)
12{
13    Console.WriteLine("Less than 30 days old");
14}

Extension Method for Reuse

csharp
1public static class DateTimeExtensions
2{
3    public static bool IsLessThanDaysOld(this DateTime date, int days)
4    {
5        return (DateTime.UtcNow - date).TotalDays < days;
6    }
7
8    public static bool IsWithinLast(this DateTime date, TimeSpan duration)
9    {
10        return DateTime.UtcNow - date < duration;
11    }
12
13    public static string TimeAgo(this DateTime date)
14    {
15        var span = DateTime.UtcNow - date;
16        if (span.TotalMinutes < 1) return "just now";
17        if (span.TotalHours < 1) return $"{span.Minutes} minutes ago";
18        if (span.TotalDays < 1) return $"{span.Hours} hours ago";
19        if (span.TotalDays < 30) return $"{span.Days} days ago";
20        if (span.TotalDays < 365) return $"{span.Days / 30} months ago";
21        return $"{span.Days / 365} years ago";
22    }
23}
24
25// Usage
26DateTime postDate = DateTime.UtcNow.AddDays(-15);
27Console.WriteLine(postDate.IsLessThanDaysOld(30));  // True
28Console.WriteLine(postDate.TimeAgo());               // "15 days ago"

Working with DateTimeOffset

For timezone-aware comparisons, use DateTimeOffset:

csharp
1DateTimeOffset postDate = new DateTimeOffset(2026, 2, 15, 10, 0, 0, TimeSpan.FromHours(-5));
2DateTimeOffset now = DateTimeOffset.UtcNow;
3
4if ((now - postDate).TotalDays < 30)
5{
6    Console.WriteLine("Less than 30 days old");
7}

Common Patterns

csharp
1// Check if a record is recent (within last N days)
2var recentOrders = orders.Where(o => (DateTime.UtcNow - o.CreatedAt).TotalDays < 30);
3
4// Check if a password has expired (older than 90 days)
5bool isExpired = (DateTime.UtcNow - user.PasswordChangedAt).TotalDays >= 90;
6
7// Check if a cache entry is stale (older than 1 hour)
8bool isStale = DateTime.UtcNow - cacheEntry.Timestamp > TimeSpan.FromHours(1);
9
10// Check if within business hours (today between 9 AM and 5 PM)
11var now = DateTime.Now;
12bool isBusinessHours = now.Hour >= 9 && now.Hour < 17
13                       && now.DayOfWeek != DayOfWeek.Saturday
14                       && now.DayOfWeek != DayOfWeek.Sunday;

LINQ with Date Filtering

csharp
1var recentPosts = posts
2    .Where(p => p.PublishedAt > DateTime.UtcNow.AddDays(-30))
3    .OrderByDescending(p => p.PublishedAt)
4    .ToList();
5
6// Group by age category
7var categorized = posts.GroupBy(p =>
8{
9    var days = (DateTime.UtcNow - p.PublishedAt).TotalDays;
10    if (days < 7) return "This week";
11    if (days < 30) return "This month";
12    if (days < 365) return "This year";
13    return "Older";
14});

Common Pitfalls

  • Using DateTime.Now instead of DateTime.UtcNow: DateTime.Now returns local time, which changes with DST. A date that is "29 days old" in local time might be "30 days old" in UTC (or vice versa) during DST transitions. Use DateTime.UtcNow for consistent server-side comparisons.
  • Using DateTime.Compare when subtraction is simpler: DateTime.Compare(a, b) only returns -1, 0, or 1 — it does not tell you how far apart the dates are. For "less than 30 days" checks, (now - date).TotalDays < 30 is more readable and directly answers the question.
  • Using .Days instead of .TotalDays on TimeSpan: TimeSpan.Days is the integer day component only (ignoring hours/minutes). TimeSpan.TotalDays includes the fractional part. A span of 29 days and 23 hours has .Days == 29 but .TotalDays == 29.96. Use .TotalDays for accurate "less than 30 days" checks.
  • Comparing DateTime and DateTimeOffset: Subtracting DateTime from DateTimeOffset (or vice versa) can silently produce wrong results because the DateTime is assumed to be local or UTC depending on its Kind. Use the same type consistently, or convert explicitly.
  • Not handling future dates: If postDate is in the future, DateTime.Now - postDate produces a negative TimeSpan. The check totalDays < 30 returns true for future dates, which may not be intended. Add totalDays >= 0 to the condition if only past dates should qualify.

Summary

  • Use (DateTime.UtcNow - date).TotalDays < 30 to check if a date is less than 30 days old
  • DateTime.Compare only returns -1/0/1 — use it when you need ordering, not duration
  • Prefer comparison operators (>, <) over DateTime.Compare for readability
  • Use DateTime.UtcNow instead of DateTime.Now to avoid DST-related bugs
  • Use .TotalDays (not .Days) on TimeSpan for accurate fractional-day comparisons
  • Create extension methods for commonly used date checks to improve code readability

Related reading
Course
Intermediate
27 lessons
14 hours
OOD Fundamentals

Master object-oriented design from first principles, SOLID, design patterns, and classic interview problems with hands-on coding.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions