Skip to content

Instantly share code, notes, and snippets.

@iwillspeak
Created July 5, 2016 08:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save iwillspeak/d02cc48f31ce5f74e9f97d75c8a98289 to your computer and use it in GitHub Desktop.
Save iwillspeak/d02cc48f31ce5f74e9f97d75c8a98289 to your computer and use it in GitHub Desktop.
Thoughts on Time
abstract class TZ
{
public abstract TimeSpan UTCOffset { get; }
}
sealed class BST : TZ
{
public override TimeSpan UTCOffset => TimeSpan.FromHours(1);
}
sealed class UTC : TZ
{
public override TimeSpan UTCOffset => TimeSpan.FromHours(0);
}
class Time<T>
where T : TZ, new()
{
public Time(long utcOffset)
{
_offset = utcOffset;
_tz = new T();
}
public Time<U> To<U>() where U : TZ, new()
{
return new Time<U>(_offset);
}
public DateTime AsDateTime => DateTime.FromBinary(_offset) + _tz.UTCOffset;
private long _offset;
private T _tz;
}
void Main()
{
var bst = new Time<BST>(DateTime.UtcNow.ToBinary());
var utc = new Time<UTC>(DateTime.UtcNow.ToBinary());
bst.AsDateTime.Dump();
utc.AsDateTime.Dump();
utc.To<BST>().AsDateTime.Dump();
}
@iwillspeak
Copy link
Author

The idea is that the timezone is part of the type of a time. This prevents a time in a given timezone being used accidentally as a value for a time in another timezone. It would probably work better in a language with a more expressive type system than C#.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment