From b3eff222b3276ea963fcee88a39164e84a3ab11c Mon Sep 17 00:00:00 2001 From: Simon Oxtoby Date: Mon, 24 Jun 2019 22:12:28 +1000 Subject: [PATCH] Fixing ToDateTime helper --- SlackNet.Tests/UtilsTests.cs | 46 ++++++++++++++++++++++++++++++++++++ SlackNet/Utils.cs | 6 +++-- 2 files changed, 50 insertions(+), 2 deletions(-) diff --git a/SlackNet.Tests/UtilsTests.cs b/SlackNet.Tests/UtilsTests.cs index 6135b3d..0e576b1 100644 --- a/SlackNet.Tests/UtilsTests.cs +++ b/SlackNet.Tests/UtilsTests.cs @@ -17,6 +17,52 @@ public void SetUp() _scheduler = new TestScheduler(); } + [Test] + public void ToDateTime_FromTimestampString_NullOrEmpty_ReturnsNull() + { + ((string)null).ToDateTime().ShouldBeNull(); + string.Empty.ToDateTime().ShouldBeNull(); + } + + [Test] + public void ToDateTime_FromTimestampString_InvalidTimestamp_ReturnsNull() + { + "foo".ToDateTime().ShouldBeNull(); + } + + [Test] + public void ToDateTime_FromTimestampString_ValidTimestamp_ReturnsDateTime() + { + "42".ToDateTime().ShouldBe(new DateTime(1970, 1, 1, 0, 0, 42)); + "-42".ToDateTime().ShouldBe(new DateTime(1969, 12, 31, 23, 59, 18)); + } + + [Test] + public void ToDateTime_FromInteger_Zero_ReturnsNull() + { + 0.ToDateTime().ShouldBeNull(); + } + + [Test] + public void ToDateTime_FromInteger_NonZero_ReturnsDateTime() + { + 42.ToDateTime().ShouldBe(new DateTime(1970, 1, 1, 0, 0, 42)); + (-42).ToDateTime().ShouldBe(new DateTime(1969, 12, 31, 23, 59, 18)); + } + + [Test] + public void ToDateTime_FromDecimal_Zero_ReturnsNull() + { + 0m.ToDateTime().ShouldBeNull(); + } + + [Test] + public void ToDateTime_FromDecimal_NonZero_ReturnsDateTime() + { + 42m.ToDateTime().ShouldBe(new DateTime(1970, 1, 1, 0, 0, 42)); + (-42m).ToDateTime().ShouldBe(new DateTime(1969, 12, 31, 23, 59, 18)); + } + [Test] public void RetryWithDelay_NoError_PassesThrough() { diff --git a/SlackNet/Utils.cs b/SlackNet/Utils.cs index 41ad102..284ff6d 100644 --- a/SlackNet/Utils.cs +++ b/SlackNet/Utils.cs @@ -17,7 +17,9 @@ public static class Utils public static DateTime? ToDateTime(this string timestamp) => string.IsNullOrEmpty(timestamp) ? null - : Decimal.Parse(timestamp).ToDateTime(); + : decimal.TryParse(timestamp, out var ts) + ? ts.ToDateTime() + : null; /// /// Converts a Slack timestamp number to a . @@ -30,7 +32,7 @@ public static class Utils /// /// If timestamp is 0, returns null, otherwise a DateTime. public static DateTime? ToDateTime(this decimal timestamp) => - timestamp == 0 + timestamp != 0 ? DateTimeOffset.FromUnixTimeMilliseconds((long)(timestamp * 1000)).UtcDateTime : (DateTime?)null;