Skip to content

DateTime

Overview

Cera provides DateTime for date and time, TimeSpan for durations, and Stopwatch for measuring elapsed time.

Creating DateTime Values

DateTime now = DateTime.Now()
DateTime utc = DateTime.UtcNow()

Accessing Components

DateTime dt = DateTime.Now()
Console.WriteLineInt(dt.Year)
Console.WriteLineInt(dt.Month) // 1-12
Console.WriteLineInt(dt.Day) // 1-31
Console.WriteLineInt(dt.Hour) // 0-23
Console.WriteLineInt(dt.Minute) // 0-59
Console.WriteLineInt(dt.Second) // 0-59
Console.WriteLineInt(dt.Millisecond) // 0-999
Console.WriteLineInt(dt.DayOfWeek) // 0=Sunday
Console.WriteLineInt(dt.DayOfYear) // 1-366

Unix Timestamps

int ms = dt.ToUnixMs()

Adding Time

DateTime later = dt.AddMs(86400000) // add one day in milliseconds

Formatting

string s = (string)dt;
Console.WriteLine(s)

TimeSpan

TimeSpan represents a duration of time:

TimeSpan span = TimeSpan.FromDays(1)
TimeSpan span2 = TimeSpan.FromHours(2)
TimeSpan span3 = TimeSpan.FromMinutes(30)
TimeSpan span4 = TimeSpan.FromSeconds(45)

TimeSpan Properties

PropertyTypeDescription
ts.TotalMillisecondsfloatTotal duration in ms
ts.TotalSecondsfloatTotal duration in seconds
ts.DaysintDays component
ts.HoursintHours component (0-23)
ts.MinutesintMinutes component (0-59)
ts.SecondsintSeconds component (0-59)

Stopwatch

Measure elapsed time:

Stopwatch sw = Stopwatch()
sw.Start()
// ... do work ...
sw.Stop()
Console.WriteLineInt(sw.ElapsedMilliseconds)
Console.WriteLine($"{sw.IsRunning}")
sw.Reset()
sw.Restart()
// ... more work ...
sw.Stop()
Console.WriteLineInt(sw.ElapsedMilliseconds)