Skip to content

Commit

Permalink
Fixing ToDateTime helper
Browse files Browse the repository at this point in the history
  • Loading branch information
soxtoby committed Jun 24, 2019
1 parent 286ddf8 commit b3eff22
Show file tree
Hide file tree
Showing 2 changed files with 50 additions and 2 deletions.
46 changes: 46 additions & 0 deletions SlackNet.Tests/UtilsTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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()
{
Expand Down
6 changes: 4 additions & 2 deletions SlackNet/Utils.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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;

/// <summary>
/// Converts a Slack timestamp number to a <see cref="DateTime"/>.
Expand All @@ -30,7 +32,7 @@ public static class Utils
/// </summary>
/// <returns>If timestamp is 0, returns null, otherwise a DateTime.</returns>
public static DateTime? ToDateTime(this decimal timestamp) =>
timestamp == 0
timestamp != 0
? DateTimeOffset.FromUnixTimeMilliseconds((long)(timestamp * 1000)).UtcDateTime
: (DateTime?)null;

Expand Down

0 comments on commit b3eff22

Please sign in to comment.