Created
December 9, 2015 16:50
-
-
Save patridge/62ee38f6778844ae0222 to your computer and use it in GitHub Desktop.
Creating Mongo ObjectIds manually (e.g., for testing) from a given DateTime object.
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
public static class DateTimeExtensions | |
{ | |
static readonly DateTime Epoch = new DateTime (1970, 1, 1, 0, 0, 0, DateTimeKind.Utc); | |
public static string AsObjectIdPrefix (this DateTime dateTime) | |
{ | |
var deltaSinceEpoch = dateTime - Epoch; | |
var seconds = (int)deltaSinceEpoch.TotalSeconds; | |
var secondsAsHex = seconds.ToString ("X").PadLeft (8, '0').ToLowerInvariant (); | |
return secondsAsHex; | |
} | |
} | |
public class DateTime_AsObjectIdPrefix | |
{ | |
[Test] | |
public void Epoch_Is00000000 () | |
{ | |
var date = new DateTime (1970, 1, 1, 0, 0, 0, DateTimeKind.Utc); | |
var expected = "00000000"; | |
var epochHex = date.AsObjectIdPrefix (); | |
Assert.That (epochHex, Is.EqualTo (expected)); | |
} | |
[Test] | |
public void SomeDate_IsExpectedValueManuallyGrabbedFromMongo () | |
{ | |
//ISODate("2015-11-25T23:01:50") | |
var date = new DateTime (2015, 11, 25, 23, 01, 50, DateTimeKind.Utc); | |
var expected = "56563dde"; | |
var epochHex = date.AsObjectIdPrefix (); | |
Assert.That (epochHex, Is.EqualTo (expected)); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment