public void ToSecondsDateTime() { // Must be UTC as we really can't rely on anything else when unit testing DateTime DateTime dt = new DateTime(2022, 2, 3, 11, 0, 0, DateTimeKind.Utc); // Cast to int as we don't really care about the milliseconds here int result = (int)UnixTimeUtils.ToSeconds(dt); // Do we have a match? Assert.AreEqual(1643886000, result); }
public void ToSecondsDateTimeOffset() { // Initialize to different DateTimeOffset representing the same point in time, but with different offsets DateTimeOffset dto1 = new DateTimeOffset(2022, 2, 3, 11, 0, 0, TimeSpan.Zero); DateTimeOffset dto2 = new DateTimeOffset(2022, 2, 3, 12, 0, 0, TimeSpan.FromHours(1)); // Cast to int as we don't really care about the milliseconds here int result1 = (int)UnixTimeUtils.ToSeconds(dto1); int result2 = (int)UnixTimeUtils.ToSeconds(dto2); // Do we have a match? Assert.AreEqual(1643886000, result1); Assert.AreEqual(1643886000, result2); }
internal static object ToFormat(DateTimeOffset value, TimeFormat format) { switch (format) { case TimeFormat.Iso8601: return(Iso8601Utils.ToString(value)); case TimeFormat.Rfc822: return(Rfc822Utils.ToString(value)); case TimeFormat.Rfc2822: return(Rfc2822Utils.ToString(value)); case TimeFormat.UnixTime: return((long)UnixTimeUtils.ToSeconds(value)); default: throw new ArgumentException("Unsupported format " + format, nameof(format)); } }
public void CurrentSeconds() { double actual = UnixTimeUtils.CurrentSeconds; // Since Unix time is calculated back to UTC, using "DateTime.Now" and "DateTime.UtcNow" should give the // same result double expected1 = UnixTimeUtils.ToSeconds(DateTime.Now); double expected2 = UnixTimeUtils.ToSeconds(DateTime.UtcNow); Assert.AreEqual(expected2, expected1); // Comparing against current time is always tricky. If this is the first test to run, there may be a ~100 ms // difference between the actual and expected timestamps. If other tests have run first, the two timestamps // so far seem to be the same ¯\_(ツ)_/¯ // Since the important part we want to test here is that the two timestamps are based on the same timezone, // we can confirm this by checking that "delta" is below 1 second. double delta1 = Math.Abs(actual - expected1); double delta2 = Math.Abs(actual - expected2); Assert.IsTrue(delta1 < 1, "#1"); Assert.IsTrue(delta2 < 1, "#2"); }
public static double GetUnixTimeFromDateTimeOffsetAsDouble(DateTimeOffset date) { return(UnixTimeUtils.ToSeconds(date)); }
public static int GetUnixTimeFromDateTimeOffset(DateTimeOffset date) { return((int)UnixTimeUtils.ToSeconds(date)); }