Skip to content
Tutorials Center
My learning

Topics

Lesson 9 of 36 ยท Syntax and Types

Nullable Values and Dates

Learn nullable value types (Integer?), HasValue and GetValueOrDefault, then work with Date, DateTime, TimeSpan, date arithmetic, formatting, parsing and time zones in Visual Basic .NET.

Two small but important topics finish the type basics. First, nullable value types: numbers and dates normally always have a value, but real data has gaps, such as a missing age or an order not yet shipped. Second, dates and times, which look simple and are famous for subtle bugs. Listings are VB.NET (read-only); each topic has a runnable C# stand-in that uses the identical System.Nullable(Of T), DateTime and TimeSpan types.

Nullable value types

A normal Integer cannot be Nothing. To say "a number, or no value", add a question mark to the type name, or use the generic form:

VB
Dim age As Integer? = Nothing
Dim score As Nullable(Of Integer) = 90

Console.WriteLine(age.HasValue)          ' False
Console.WriteLine(score.HasValue)        ' True
Console.WriteLine(score.Value)           ' 90
Console.WriteLine(age.GetValueOrDefault())     ' 0
Console.WriteLine(age.GetValueOrDefault(-1))   ' -1
Console.WriteLine(If(age, -1))                 ' -1  (two-argument If)

Reading .Value when there is no value throws InvalidOperationException, so test HasValue first or use GetValueOrDefault. In VB, Nothing assigned to a value-type variable means its default value (0 for Integer), but for Integer? it means "no value".

Operators and null

Arithmetic with a missing value gives a missing value: age + 1 is Nothing when age has no value. Comparisons follow SQL-like three-valued logic in VB: age = 5 with no value is neither True nor False, and an If treats it as false. To test for absence write age.HasValue or age Is Nothing.

Databases return DBNull, not Nothing, so you will meet Nullable when you read optional columns (see the chapter on files and databases).

C# Stand-in (C#): nullable values and defaults

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Dates and times

The VB keyword Date is an alias for System.DateTime: a point in time with ticks of 100 nanoseconds, stored with a Kind (Local, Utc or Unspecified). A date literal is written between # signs in US format #month/day/year#:

VB
Dim d1 As Date = #3/15/2025#
Dim d2 As Date = #3/15/2025 2:30:00 PM#
Dim d3 As New Date(2025, 3, 15)                ' year, month, day
Dim now1 As Date = Date.Now                    ' local time
Dim utc1 As Date = Date.UtcNow                 ' universal time
Dim today1 As Date = Date.Today                ' today at 00:00

Parts and arithmetic

VB
Dim due As Date = #3/15/2025#
Console.WriteLine(due.Year)            ' 2025
Console.WriteLine(due.Month)           ' 3
Console.WriteLine(due.Day)             ' 15
Console.WriteLine(due.DayOfWeek)       ' Saturday
Console.WriteLine(due.DayOfYear)       ' 74

Dim later As Date = due.AddDays(30)    ' returns a NEW date
Dim prev As Date = due.AddMonths(-1)
Dim span As TimeSpan = later - due     ' subtracting dates gives a TimeSpan
Console.WriteLine(span.TotalDays)      ' 30

Like strings, dates are immutable: AddDays returns a new value. A TimeSpan represents a length of time (TimeSpan.FromHours(1.5), New TimeSpan(2, 30, 0)), with Days, Hours, Minutes and the Total... properties that include fractions.

C# Stand-in (C#): date arithmetic

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Formatting and parsing

Use format strings for output: d.ToString("yyyy-MM-dd"), "dd/MM/yyyy", "MMMM d, yyyy", "HH:mm:ss", and the round-trip format "o". Standard patterns such as "d" (short date) depend on the culture. For files, logs and APIs always use the invariant culture or ISO 8601.

VB
Imports System.Globalization

Dim text As String = "2025-03-15"
Dim parsed As Date
If Date.TryParseExact(text, "yyyy-MM-dd", CultureInfo.InvariantCulture,
                      DateTimeStyles.None, parsed) Then
    Console.WriteLine(parsed.ToString("MMMM d, yyyy", CultureInfo.InvariantCulture))
End If

Date.TryParse is forgiving and culture-dependent: "03/04/2025" may mean March 4 or April 3 depending on the machine. Prefer TryParseExact with an explicit format for known layouts.

C# Stand-in (C#): parsing and formatting with an explicit format

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Time zones: DateTimeOffset

A DateTime does not carry its offset from UTC. When you store or exchange moments, prefer DateTimeOffset (date, time and offset together) or store UTC and convert for display. Date.Now is the machine's local time; use Date.UtcNow for timestamps and elapsed-time comparisons. Measure durations with Stopwatch, not with date subtraction, because clocks can change.

VB
Dim stamp As DateTimeOffset = DateTimeOffset.UtcNow
Console.WriteLine(stamp.ToString("o"))

Dim sw As Stopwatch = Stopwatch.StartNew()
' ... work ...
Console.WriteLine($"{sw.ElapsedMilliseconds} ms")

Daylight-saving transitions create hours that do not exist or exist twice, so avoid doing arithmetic on local times when exactness matters.

Common mistakes

  • Reading .Value of an empty nullable without checking HasValue.
  • Writing date literals in your local format; the #...# literal is always month/day/year.
  • Comparing Date.Now values for equality, or storing local time instead of UTC.
  • Using TryParse for fixed-format dates instead of TryParseExact.
  • Forgetting that AddDays and friends do not change the original date.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does Dim x As Integer? = Nothing mean?

    For a nullable value type, Nothing means 'no value', unlike a plain Integer where it would mean 0.
  2. 2. What happens when you read .Value of a nullable with no value?

    Check HasValue first or use GetValueOrDefault or the two-argument If.
  3. 3. What type does subtracting one Date from another give?

    The difference between two dates is a length of time: a TimeSpan.
  4. 4. In which order is a VB date literal written?

    Date literals always use US month/day/year order, independent of the machine's culture.
  5. 5. Which is best for storing a timestamp that must mean the same moment everywhere?

    UTC (or a value with an explicit offset) is unambiguous; local time depends on the machine and daylight saving.

Summary

  • Add ? (or use Nullable(Of T)) to let a value type hold "no value"; check HasValue before .Value.
  • Date is System.DateTime; literals are #month/day/year#; AddDays and friends return new values.
  • Subtracting dates yields a TimeSpan; use TotalDays, TotalHours for fractional amounts.
  • Format and parse with explicit patterns and CultureInfo.InvariantCulture; prefer TryParseExact.
  • Store UTC or DateTimeOffset; measure durations with Stopwatch.

Next: If and Select Case