Date, time, numbers and regex
Every real app handles dates and times, money, IDs and text validation, and each one has a classic trap: DateTime comparisons that ignore time zones, double rounding errors in bills, and weak randomness for OTPs. This video covers the right .NET types for each.
37.1 Why is it used?
- Deadlines, expiries and schedules must be correct regardless of the server's time zone (laptop on IST, cloud on UTC).
- Users in different countries must see their own local time and number format.
- Money must be exact to the paisa; binary floating point is not.
- Business logic that depends on "now" must be testable without waiting days.
- IDs, random picks and input validation (PIN codes, mobile numbers) appear in almost every app.
37.2 The bug: the order is late for no reason
- now is DateTime.Now (Local), due is UtcNow + 2 hours (Utc).
- The deadline is 2 hours away, but the output says Late? True and Hours left -3.5.
C#
var now = DateTime.Now;var due = DateTime.UtcNow.AddHours(2); Console.WriteLine($"Now: {now:HH:mm} {now.Kind}");Console.WriteLine($"Due: {due:HH:mm} {due.Kind}");Console.WriteLine($"Late? {now > due}");Console.WriteLine( $"Hours left: {(due - now).TotalHours:F1}");Output
$ dotnet run Deadline.csNow: 01:07 LocalDue: 21:37 UtcLate? TrueHours left: -3.5- Step 1
1.DateTime stores a value + a Kind label
- Step 2
2.Compare and subtract ignore Kind
- Step 3
3.IST machine: local is 5:30 ahead of UTC
- Step 4
4.2 h - 5.5 h = -3.5 h, Late? True
- Step 5
5.Server on UTC gives a different result
Same code, one result on the laptop, another on the server
37.3 Fix: DateTimeOffset
- DateTimeOffset stores the time together with its offset from UTC (+05:30, +00:00).
- Comparisons first bring both values to the same instant: Late? False, Hours left 2.0.
- Use DateTimeOffset (or DateTime in UTC) for every real moment in time.
C#
var now = DateTimeOffset.Now;var due = DateTimeOffset.UtcNow.AddHours(2); Console.WriteLine($"Now: {now:HH:mm zzz}");Console.WriteLine($"Due: {due:HH:mm zzz}");Console.WriteLine($"Late? {now > due}");Console.WriteLine( $"Hours left: {(due - now).TotalHours:F1}");Output
$ dotnet run OffsetFix.csNow: 01:07 +05:30Due: 21:37 +00:00Late? FalseHours left: 2.037.4 Time zones: TimeZoneInfo
- FindSystemTimeZoneById("Asia/Kolkata") uses IANA ids, which work on Windows and Linux.
- ConvertTime turns one instant into each user's local time: 14:00 UTC = 19:30 IST = 09:00 New York.
- TimeZoneInfo handles daylight saving, so never hardcode offsets.
C#
var india = TimeZoneInfo .FindSystemTimeZoneById("Asia/Kolkata");var us = TimeZoneInfo .FindSystemTimeZoneById("America/New_York"); var start = new DateTimeOffset( 2026, 11, 7, 14, 0, 0, TimeSpan.Zero);var ist = TimeZoneInfo.ConvertTime(start, india);var est = TimeZoneInfo.ConvertTime(start, us); const string f = "dd MMM, HH:mm zzz";Console.WriteLine($"UTC: {start.ToString(f)}");Console.WriteLine($"India: {ist.ToString(f)}");Console.WriteLine($"US: {est.ToString(f)}");Output
$ dotnet run TimeZones.csUTC: 07 Nov, 14:00 +00:00India: 07 Nov, 19:30 +05:30US: 07 Nov, 09:00 -05:0037.5 DateOnly and TimeOnly
- DateOnly for a pure date (delivery date): no time zone confusion. 7 Nov + 5 days = 12 Nov 2026, a Thursday.
- TimeOnly for a time of day (shop hours). IsBetween(10:00, 22:00) for 23:15 is False.
- Subtracting TimeOnly values gives a TimeSpan (12:00:00).
C#
var orderDate = new DateOnly(2026, 11, 7);var delivery = orderDate.AddDays(5); Console.WriteLine($"{delivery:dd MMM yyyy}");Console.WriteLine(delivery.DayOfWeek); var open = new TimeOnly(10, 0);var close = new TimeOnly(22, 0);var at = new TimeOnly(23, 15); Console.WriteLine(at.IsBetween(open, close));Console.WriteLine(close - open);Output
$ dotnet run DateOnlyDemo.cs12 Nov 2026ThursdayFalse12:00:0037.6 TimeProvider: testable time
- DateTime.UtcNow inside a class makes "expires after N days" hard to test.
- TimeProvider (.NET 8) abstracts the current time; inject it via the constructor.
- Production: TimeProvider.System. Tests: FakeTimeProvider (Microsoft.Extensions.TimeProvider.Testing).
- clock.Advance(3 days) makes the coupon invalid instantly, no waiting.
C#
using Microsoft.Extensions.Time.Testing; var clock = new FakeTimeProvider();var coupon = new Coupon(clock, days: 2);Console.WriteLine($"Day 0: {coupon.IsValid()}");clock.Advance(TimeSpan.FromDays(3));Console.WriteLine($"Day 3: {coupon.IsValid()}"); class Coupon(TimeProvider time, int days){ readonly DateTimeOffset expiresAt = time.GetUtcNow().AddDays(days); public bool IsValid() => time.GetUtcNow() < expiresAt;}Output
$ dotnet run Coupon.csDay 0: TrueDay 3: False- Step 1
1.Input: take it with its offset
- Step 2
2.Store: UTC or DateTimeOffset
- Step 3
3.Logic: current time from TimeProvider
- Step 4
4.Display: TimeZoneInfo converts to the user's zone (IST)
Convert only at the edges
37.7 Comparison: date/time types
| Type | Stores | Use for |
|---|---|---|
| DateTime | Value + Kind label (ignored in math) | Legacy APIs; only in UTC if used |
| DateTimeOffset | Value + offset from UTC | Exact moments: orders, deadlines, logs |
| DateOnly | Date only | Birthdays, delivery dates |
| TimeOnly | Time of day only | Shop hours, alarms |
| TimeZoneInfo | Zone rules incl. daylight saving | Converting for display |
| TimeProvider | Source of "now" | Testable business logic |
37.8 Rounding and money
- Checkpoint: Math.Round(2.5) = 2 and Math.Round(3.5) = 4: banker's rounding (midpoint goes to the nearest even number).
- School-style rounding: MidpointRounding.AwayFromZero gives 3.
- double uses binary fractions: 0.1 + 0.2 = 0.30000000000000004, and 18% GST on 13.25 rounds to 2.38.
- decimal does exact decimal math; with AwayFromZero the GST is 2.39, correct for a bill.
C#
Console.WriteLine(Math.Round(2.5));Console.WriteLine(Math.Round(3.5));Console.WriteLine(Math.Round(2.5, MidpointRounding.AwayFromZero));Output
$ dotnet run Rounding.cs243C#
double total = 0.1 + 0.2;Console.WriteLine(total);// 0.30000000000000004 double gst = 13.25 * 0.18;Console.WriteLine(Math.Round(gst, 2));// 2.38C#
decimal total = 0.1m + 0.2m;Console.WriteLine(total);// 0.3 decimal gst = 13.25m * 0.18m;Console.WriteLine(Math.Round(gst, 2, MidpointRounding.AwayFromZero));// 2.3937.9 Culture and format strings
- "C" with en-IN gives the rupee sign and lakh-style grouping; en-US gives dollars and million-style grouping.
- Custom formats like "dd MMM yyyy" give 07 Nov 2026; "d" in en-US gives 11/7/2026.
- Parse data from APIs and files with CultureInfo.InvariantCulture so the server's culture never changes the result.
C#
using System.Globalization; var ind = new CultureInfo("en-IN");var us = new CultureInfo("en-US");decimal price = 1234567.5m;var d = new DateTime(2026, 11, 7); Console.WriteLine(price.ToString("C", ind));Console.WriteLine(price.ToString("C", us));Console.WriteLine(price.ToString("N0", ind));Console.WriteLine(d.ToString("dd MMM yyyy", ind));Console.WriteLine(d.ToString("d", us));Console.WriteLine(decimal.Parse("99.50", CultureInfo.InvariantCulture));Output
$ dotnet run Formats.cs₹12,34,567.50$1,234,567.5012,34,56807 Nov 202611/7/202699.5037.10 Guid and Random.Shared
- Guid.NewGuid() is a random version 4 Guid: good for trace ids.
- Guid.CreateVersion7() (.NET 9) starts with the current time, so IDs share a prefix and stay roughly sorted in a database index.
- Random.Shared is a thread-safe shared instance, fine for games like a lucky spin.
- For OTPs, tokens and keys use RandomNumberGenerator, which is cryptographically secure.
C#
var traceId = Guid.NewGuid();var orderA = Guid.CreateVersion7();var orderB = Guid.CreateVersion7(); Console.WriteLine(traceId);Console.WriteLine(orderA);Console.WriteLine(orderB); string[] prizes = ["Cashback", "Coupon", "Retry"];int pick = Random.Shared.Next(prizes.Length);Console.WriteLine($"Spin: {prizes[pick]}");Output
$ dotnet run Ids.cs8937c0ed-d115-4190-83e0-423e44fbbb7901a1b25e-4e7b-7594-a397-55e5c18df11e01a1b25e-4e7b-7831-b3db-ce7a4ef7a563Spin: Retry37.11 Regex basics: GeneratedRegex
- Indian PIN: ^[1-9]\d{5}$ (6 digits, not starting with 0). 110001 True, 011001 False.
- Mobile: \b[6-9]\d{9}\b (10 digits starting 6-9); Matches pulls both numbers out of the message.
- [GeneratedRegex] on a static partial method generates fast matching code at build time.
C#
using System.Text.RegularExpressions; Console.WriteLine(Rx.Pin().IsMatch("110001"));Console.WriteLine(Rx.Pin().IsMatch("011001"));var msg = "Call 9876543210 or 8123456789";foreach (Match m in Rx.Mobile().Matches(msg)) Console.WriteLine(m.Value); static partial class Rx{ [GeneratedRegex(@"^[1-9]\d{5}$")] public static partial Regex Pin(); [GeneratedRegex(@"\b[6-9]\d{9}\b")] public static partial Regex Mobile();}Output
$ dotnet run Patterns.csTrueFalse9876543210812345678937.12 Common mistakes
- Comparing DateTime values with different Kinds, or using DateTime.Now on servers.
- Hardcoding +5:30 instead of using TimeZoneInfo.
- double for money, or relying on the default banker's rounding for bills.
- Parsing API data with the current culture instead of InvariantCulture.
- Myth: Random is fine for OTPs (use RandomNumberGenerator). Myth: UtcNow means time zones are done (you still convert on display).
37.13 Interview tips
- DateTime has a value and a Kind that operations ignore; DateTimeOffset keeps its UTC offset and represents an exact moment.
- Store in UTC / DateTimeOffset, get now from TimeProvider so tests control time, convert with TimeZoneInfo on display.
- Money: decimal with an explicit MidpointRounding; Math.Round defaults to banker's rounding.
- Display with a culture, parse with InvariantCulture; Guid v7 for sortable IDs, GeneratedRegex for fast validation.