Parsing & offsets in C#
Exact parsing, and offsets that pin a moment to the globe.
using System.Globalization;
var stamp = DateTime.ParseExact("2026-08-01 14:30",
"yyyy-MM-dd HH:mm", CultureInfo.InvariantCulture);
Console.WriteLine(stamp.DayOfWeek);
// an offset makes "when" unambiguous across time zones
var utc = new DateTimeOffset(stamp, TimeSpan.Zero);
Console.WriteLine(utc.ToUnixTimeSeconds());
if (!DateTime.TryParse("not a date", out _))
{
Console.WriteLine("TryParse said no, quietly");
}
How it works
ParseExactwith an invariant culture takes no format guesses.DateTimeOffsetplusToUnixTimeSecondsis the interchange path.TryParsewith a discard rejects bad input without ceremony.
Keywords and builtins used here
ifnewoutusingvar
The run, in numbers
- Lines
- 14
- Characters to type
- 418
- Tokens
- 75
- Three-star pace
- 85 tpm
At the three-star pace of 85 tokens a minute, this run takes about 53 seconds.
Step 3 of 3 in Dates & times, step 9 of 17 in The .NET library.