Example 1 — Unspecified Round Trip
Save an Unspecified value as a long and restore it.
using System;
class Program {
static void Main() {
DateTime dt = new DateTime(2026, 11, 18, 14, 30, 45);
long bin = dt.ToBinary();
DateTime back = DateTime.FromBinary(bin);
Console.WriteLine(bin);
Console.WriteLine(back == dt);
Console.WriteLine(back.Kind);
}
}
639306090450000000
True
Unspecified
How It Works
- ToBinary first. The number
639306090450000000 is the tick count for this moment. - Unspecified is plain ticks. With Kind Unspecified, the binary form equals
Ticks. - Back to DateTime.
FromBinary gives a value equal to the original, so the check prints True. - Kind kept. The restored value is still
Unspecified.
Example 2 — Utc Round Trip
Show that the binary form of a Utc value is larger and that Kind is restored.
using System;
class Program {
static void Main() {
DateTime utc = new DateTime(2026, 11, 18, 14, 30, 45, DateTimeKind.Utc);
long bin = utc.ToBinary();
DateTime back = DateTime.FromBinary(bin);
Console.WriteLine(bin);
Console.WriteLine(back.Kind);
Console.WriteLine(back == utc);
}
}
5250992108877387904
Utc
True
How It Works
- Bigger number.
5250992108877387904 is the ticks plus 4611686018427387904, a bit set to mean Utc. - Kind stored. The two top bits of the number say Unspecified, Utc, or Local.
- Restored Kind.
back.Kind prints Utc, which a plain tick count could not keep. - Equal value. The ticks match too, so
== prints True.
Example 3 — Store the Number as Text
Write the number to text, read it back, and restore the date. Also show zero.
using System;
using System.Globalization;
class Program {
static string Show(DateTime d) => d.ToString("yyyy-MM-dd HH:mm:ss", CultureInfo.InvariantCulture);
static void Main() {
DateTime dt = new DateTime(2026, 11, 18, 14, 30, 45);
string saved = dt.ToBinary().ToString(CultureInfo.InvariantCulture);
long number = long.Parse(saved, CultureInfo.InvariantCulture);
Console.WriteLine(Show(DateTime.FromBinary(number)));
Console.WriteLine(Show(DateTime.FromBinary(0)));
}
}
2026-11-18 14:30:45
0001-01-01 00:00:00
How It Works
- Number to text. The long is written with the invariant culture so there are no group separators.
- Text to number.
long.Parse returns the same number. - Date restored. The first line shows the original date and time.
- Zero. A binary value of 0 means zero ticks, which is January 1 of year 1 (
DateTime.MinValue).