8. DateTime, Regex & Utilities


Part 1: DateTime & Time Management

1. DateTime Struct

Creating DateTime

// Constructor
DateTime dt1 = new DateTime(2024, 12, 17);                    // Date only
DateTime dt2 = new DateTime(2024, 12, 17, 14, 30, 0);         // Date and time
DateTime dt3 = new DateTime(2024, 12, 17, 14, 30, 0, 500);    // With milliseconds

// Current date/time
DateTime now = DateTime.Now;              // Local time
DateTime utcNow = DateTime.UtcNow;        // UTC time
DateTime today = DateTime.Today;          // Today at midnight (00:00:00)

// Parsing
DateTime dt4 = DateTime.Parse("12/17/2024");
DateTime dt5 = DateTime.Parse("2024-12-17T14:30:00");

// Safe parsing
if (DateTime.TryParse("12/17/2024", out DateTime result))
{
    Console.WriteLine(result);
}

// Exact format
DateTime dt6 = DateTime.ParseExact(
    "17-12-2024", 
    "dd-MM-yyyy", 
    CultureInfo.InvariantCulture);

// Try parse exact
if (DateTime.TryParseExact(
    "17-12-2024", 
    "dd-MM-yyyy", 
    CultureInfo.InvariantCulture,
    DateTimeStyles.None,
    out DateTime exactResult))
{
    Console.WriteLine(exactResult);
}

// Min and Max values
DateTime min = DateTime.MinValue;  // 01/01/0001 00:00:00
DateTime max = DateTime.MaxValue;  // 12/31/9999 23:59:59

DateTime Properties

DateTime Methods

DateTime Quick Reference Table

Property/Method
Description
Example

DateTime.Now

Current local time

DateTime.Now

DateTime.UtcNow

Current UTC time

DateTime.UtcNow

DateTime.Today

Today at midnight

DateTime.Today

Year, Month, Day

Date components

dt.Year → 2024

Hour, Minute, Second

Time components

dt.Hour → 14

DayOfWeek

Day of week enum

dt.DayOfWeek → Tuesday

DayOfYear

Day number (1-366)

dt.DayOfYear → 352

AddDays(n)

Add days

dt.AddDays(7)

AddMonths(n)

Add months

dt.AddMonths(1)

AddYears(n)

Add years

dt.AddYears(1)

Subtract(date)

Time difference

date2 - date1 → TimeSpan

CompareTo(date)

Compare dates

Returns -1, 0, or 1


2. DateTimeOffset (C# 2.0+)

Purpose: DateTime with time zone offset

DateTime vs DateTimeOffset:

Feature
DateTime
DateTimeOffset

Time zone info

Kind property only

Explicit offset

Precision

Local/UTC/Unspecified

Exact moment in time

Use when

Local times, dates only

API responses, logging, distributed systems

Best for

UI, user input

Backend, databases, APIs

When to use DateTimeOffset:

  • ✅ Storing timestamps in databases

  • ✅ API responses/requests

  • ✅ Logging across time zones

  • ✅ Distributed systems


3. DateOnly & TimeOnly (.NET 6.0+)

Use Cases:

  • DateOnly - Birthdays, holidays, appointment dates

  • TimeOnly - Business hours, schedules, alarms


4. TimeSpan Struct

Creating TimeSpan

TimeSpan Properties

TimeSpan Operations


5. DateTime Formatting

Standard Format Strings

Standard Format Strings Table

Format
Name
Example Output

d

Short date

12/17/2024

D

Long date

Tuesday, December 17, 2024

t

Short time

2:30 PM

T

Long time

2:30:45 PM

f

Full (short time)

Tuesday, December 17, 2024 2:30 PM

F

Full (long time)

Tuesday, December 17, 2024 2:30:45 PM

g

General (short)

12/17/2024 2:30 PM

G

General (long)

12/17/2024 2:30:45 PM

M or m

Month day

December 17

Y or y

Year month

December 2024

o or O

Round-trip (ISO 8601)

2024-12-17T14:30:45.0000000

R or r

RFC1123

Tue, 17 Dec 2024 14:30:45 GMT

s

Sortable

2024-12-17T14:30:45

u

Universal sortable

2024-12-17 14:30:45Z

Custom Format Strings

Common Scenarios


Part 2: Regular Expressions

6. Regex Class (System.Text.RegularExpressions)

What are Regular Expressions? Patterns for matching text.

When to use Regex:

  • ✅ Validating input (email, phone, etc.)

  • ✅ Finding patterns in text

  • ✅ Replacing text based on patterns

  • ✅ Splitting strings by complex patterns

  • ❌ Simple string operations (use string methods)


7. Character Classes

Character Classes Reference

Pattern
Matches
Example

.

Any character (except newline)

c.t → "cat", "cut"

[abc]

Any of a, b, or c

[cb]at → "cat", "bat"

[^abc]

Not a, b, or c

[^c]at → "bat", "hat"

[a-z]

Any lowercase letter

[a-z]+ → "hello"

[A-Z]

Any uppercase letter

[A-Z]+ → "HELLO"

[0-9]

Any digit

[0-9]+ → "123"

\d

Digit [0-9]

\d+ → "123"

\D

Non-digit

\D+ → "abc"

\w

Word character [a-zA-Z0-9_]

\w+ → "hello_123"

\W

Non-word character

\W+ → "@#$"

\s

Whitespace

\s+ → " "

\S

Non-whitespace

\S+ → "hello"


8. Quantifiers

Quantifiers Reference

Quantifier
Matches
Example

*

0 or more

a* → "", "a", "aaa"

+

1 or more

a+ → "a", "aaa"

?

0 or 1

colou?r → "color", "colour"

{n}

Exactly n

a{3} → "aaa"

{n,}

n or more

a{2,} → "aa", "aaa"

{n,m}

Between n and m

a{2,4} → "aa", "aaa", "aaaa"

*?

Lazy 0 or more

<.*?> → shortest match

+?

Lazy 1 or more

.+? → shortest match

??

Lazy 0 or 1

colou??r → shortest match


9. Anchors


10. Groups


11. Alternation


12. Regex Methods


13. RegexOptions Enum


14. Common Regex Patterns

Common Patterns Reference

Pattern Type
Regex
Matches

Email

^[\w.+-]+@[\w.-]+\.\w{2,}$

user@example.com

Phone (US)

^\d{3}-\d{3}-\d{4}$

555-123-4567

URL

https?://[^\s]+

https://example.com

IP Address

^(\d{1,3}\.){3}\d{1,3}$

192.168.1.1

ZIP Code

^\d{5}(-\d{4})?$

12345 or 12345-6789

Hex Color

^#[0-9A-Fa-f]{6}$

#FF5733

Date (ISO)

^\d{4}-\d{2}-\d{2}$

2024-12-17


Part 3: Math & Random

15. Math Class

Math Methods Reference

Method
Description
Example

Abs(x)

Absolute value

Math.Abs(-5) → 5

Sqrt(x)

Square root

Math.Sqrt(16) → 4

Pow(x, y)

x to power y

Math.Pow(2, 3) → 8

Round(x)

Round to nearest

Math.Round(3.5) → 4

Floor(x)

Round down

Math.Floor(3.9) → 3

Ceiling(x)

Round up

Math.Ceiling(3.1) → 4

Min(x, y)

Minimum

Math.Min(5, 10) → 5

Max(x, y)

Maximum

Math.Max(5, 10) → 10

Clamp(x, min, max)

Limit to range

Math.Clamp(15, 0, 10) → 10


16. Rounding Comparison

Rounding Behavior Table

Value
ToEven
AwayFromZero
ToZero
Floor
Ceiling

2.5

2

3

2

2

3

3.5

4

4

3

3

4

-2.5

-2

-3

-2

-3

-2

-3.5

-4

-4

-3

-4

-3


17. Random Class

Thread Safety:

  • Random - NOT thread-safe (use separate instance per thread)

  • Random.Shared (.NET 6.0+) - Thread-safe

Common Patterns:


18. Guid Struct


Part 4: String Utilities

19. String.Format() and Composite Formatting


20. StringBuilder (Brief Reference)

When to use:

  • ✅ Building strings in loops

  • ✅ Many concatenations (>5)

  • ✅ Dynamic string construction

  • ❌ Few concatenations (string + is fine)


21. String Comparison

StringComparison Options

Option
Case-Sensitive
Culture-Specific
Use When

Ordinal

Yes

No

File paths, IDs, exact matching

OrdinalIgnoreCase

No

No

File names, configuration keys

CurrentCulture

Yes

Yes

User-facing text

CurrentCultureIgnoreCase

No

Yes

User-facing search

InvariantCulture

Yes

No

Persistent storage

InvariantCultureIgnoreCase

No

No

Case-insensitive storage keys

Best Practice:

  • Use Ordinal or OrdinalIgnoreCase for non-linguistic comparisons

  • Use CurrentCulture for user-facing text


Quick Reference Summary

DateTime

  • DateTime.Now / DateTime.UtcNow / DateTime.Today

  • Add/subtract: AddDays(), AddMonths(), Subtract()

  • Format: ToString("yyyy-MM-dd") or standard formats (d, D, t, T, etc.)

  • Use DateTimeOffset for time zones

  • Use DateOnly / TimeOnly (.NET 6+) for date/time only

TimeSpan

  • Create: TimeSpan.FromDays(), FromHours(), etc.

  • Properties: Days, Hours, TotalDays, TotalHours

  • Operations: +, -, *, /

Regex

  • Test: Regex.IsMatch(text, pattern)

  • Find: Regex.Match(text, pattern)

  • Replace: Regex.Replace(text, pattern, replacement)

  • Patterns: \d (digit), \w (word), \s (space), [a-z] (range)

  • Quantifiers: * (0+), + (1+), ? (0-1), {n} (exactly n)

Math

  • Rounding: Round(), Floor(), Ceiling(), Truncate()

  • Power: Pow(), Sqrt(), Cbrt()

  • Min/Max: Min(), Max(), Clamp()

Random

  • Next() - random int

  • NextDouble() - random double (0.0-1.0)

  • Random.Shared (.NET 6+) - thread-safe

String Utilities

  • Format: String.Format("{0:N2}", value)

  • StringBuilder: Use for many concatenations

  • Comparison: Use StringComparison.OrdinalIgnoreCase for case-insensitive


Guide Complete! These utilities are essential for everyday C# programming! 📘

Last updated