Created
July 5, 2016 08:39
-
-
Save iwillspeak/d02cc48f31ce5f74e9f97d75c8a98289 to your computer and use it in GitHub Desktop.
Thoughts on Time
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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#.