Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feature/add unix timestamp #10

Merged
merged 13 commits into from
May 13, 2019
13 changes: 11 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
# moment.net

[![Build Status](https://travis-ci.org/bolorundurowb/moment.net.svg?branch=master)](https://travis-ci.org/bolorundurowb/moment.net) [![Coverage Status](https://coveralls.io/repos/github/bolorundurowb/moment.net/badge.svg)](https://coveralls.io/github/bolorundurowb/moment.net) [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](LICENSE)
[![Build Status](https://travis-ci.org/bolorundurowb/moment.net.svg?branch=master)](https://travis-ci.org/bolorundurowb/moment.net) [![Coverage Status](https://coveralls.io/repos/github/bolorundurowb/moment.net/badge.svg)](https://coveralls.io/github/bolorundurowb/moment.net) [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](LICENSE) [![NuGet Badge](https://buildstats.info/nuget/moment.net)](https://www.nuget.org/packages/moment.net)


This library aims to port as many bits of functionality from moment.js as is necessary. A few have been ported thus far `FromNow`, `From`, `ToNow`, `To`, `StartOf`, `EndOf` and `CalendarTime``.
This library aims to port as many bits of functionality from moment.js as is necessary. A few have been ported thus far `FromNow`, `From`, `ToNow`, `To`, `StartOf`, `EndOf` and `CalendarTime`.

## Usages

Expand Down Expand Up @@ -66,4 +66,13 @@ var endDateTime = new DateTime(2012, 12, 13);
var calendarTime = startDateTime.CalendarTime(endDateTime); // Tomorrow at 00:00 AM
calendarTime = endDateTime.CalendarTime(startDateTime); // Yesterday at 00:00 AM
calendarTime = startDateTime.CalendarTime(sameDay); // Today at 12:00 PM
```

#### UnixTime
UnixTime supports retrieving the number of seconds or milliseconds that have elapsed since the [unix epoch](https://en.wikipedia.org/wiki/Unix_time)

```csharp
var dateTime = new DateTime(1971, 01, 01, 0, 0, 0, DateTimeKind.Utc);
var millisecondsElapsed = dateTime.UnixTimestampInMilliseconds(); // 31536000000
var secondsElapsed = dateTime.UnixTimestampInSeconds(); // 31536000
```
42 changes: 35 additions & 7 deletions src/RelativeTime.cs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ namespace moment.net
{
public static class RelativeTime
{
private static readonly DateTime UnixEpoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
private const double DaysInAYear = 365.2425; // see https://en.wikipedia.org/wiki/Gregorian_calendar
private const double DaysInAMonth = DaysInAYear / 12;

Expand Down Expand Up @@ -36,7 +37,7 @@ public static DateTime StartOf(this DateTime This, DateTimeAnchor timeAnchor, Cu
case DateTimeAnchor.Minute:
return new DateTime(This.Year, This.Month, This.Day, This.Hour, This.Minute, 0);
case DateTimeAnchor.Hour:
return new DateTime(This.Year, This.Month, This.Day, This.Hour,0,0);
return new DateTime(This.Year, This.Month, This.Day, This.Hour, 0, 0);
case DateTimeAnchor.Day:
return new DateTime(This.Year, This.Month, This.Day);
case DateTimeAnchor.Week:
Expand Down Expand Up @@ -178,21 +179,49 @@ public static string CalendarTime(this DateTime This, CalendarTimeFormats format
{
return endDate.ToString(formats.NextDay);
}

if (startDate.AddDays(-1).Date == endDate.Date)
{
return endDate.ToString(formats.LastDay);
}

if (timeDiff.TotalDays > 1 && timeDiff.TotalDays < 7)
{
return endDate.ToString(formats.NextWeek);
}

if (timeDiff.TotalDays >= -6 && timeDiff.TotalDays < -1)
{
return endDate.ToString(formats.LastWeek);
}

return endDate.ToString(formats.EverythingElse);
}

/// <summary>
/// Get the total number of seconds since the unix epoch
/// </summary>
/// <param name="This">DateTime instance to compare the unix epoch to</param>
/// <returns>A double value indicating the number of seconds</returns>
public static double UnixTimestampInSeconds(this DateTime This)
{
var dateInstance = This.Kind == DateTimeKind.Utc ? This : This.ToUniversalTime();
var timeSpan = dateInstance - UnixEpoch;
return timeSpan.TotalSeconds;
}

/// <summary>
/// Get the total number of milliseconds since the unix epoch
/// </summary>
/// <param name="This">DateTime instance to compare the unix epoch to</param>
/// <returns>A double value indicating the number of milliseconds</returns>
public static double UnixTimestampInMilliseconds(this DateTime This)
{
var dateInstance = This.Kind == DateTimeKind.Utc ? This : This.ToUniversalTime();
var timeSpan = dateInstance - UnixEpoch;
return timeSpan.TotalMilliseconds;
}

private static string ParseFromPastTimeSpan(TimeSpan timeSpan)
{
return $"{ParseTimeDifference(timeSpan)} ago";
Expand Down Expand Up @@ -281,9 +310,9 @@ private static string ParseTimeDifference(TimeSpan timeSpan)
/// <returns></returns>
private static DateTime GetFirstDateInWeek(DateTime dayInWeek, CultureInfo cultureInfo)
{
DayOfWeek firstDayOfWeek = cultureInfo.DateTimeFormat.FirstDayOfWeek;
DateTime firstDateInWeek = dayInWeek.Date;
int diff = (int)firstDateInWeek.DayOfWeek - (int)firstDayOfWeek;
var firstDayOfWeek = cultureInfo.DateTimeFormat.FirstDayOfWeek;
var firstDateInWeek = dayInWeek.Date;
var diff = (int) firstDateInWeek.DayOfWeek - (int) firstDayOfWeek;
var value = firstDateInWeek.AddDays(-(Math.Abs(diff)));
return value;
}
Expand All @@ -297,9 +326,8 @@ private static DateTime GetFirstDateInWeek(DateTime dayInWeek, CultureInfo cultu
/// <returns>The date of the last day in a week</returns>
private static DateTime GetLastDateInWeek(DateTime dayInWeek, CultureInfo cultureInfo)
{
DateTime firstDayInWeek = GetFirstDateInWeek(dayInWeek, cultureInfo);
var firstDayInWeek = GetFirstDateInWeek(dayInWeek, cultureInfo);
return firstDayInWeek.AddDays(6);
}

}
}
}
6 changes: 3 additions & 3 deletions src/moment.net.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -2,17 +2,17 @@

<PropertyGroup>
<TargetFrameworks>netstandard1.1;netstandard2.0</TargetFrameworks>
<PackageVersion>1.0.0</PackageVersion>
<PackageVersion>1.1.0</PackageVersion>
<Title>moment.net</Title>
<Authors>bolorundurowb YemiKudaisi</Authors>
<Description>A library aimed at adding in some relevanyt fundtionality as seen in moment.js</Description>
<Description>A library aimed at adding in some relevant functionality as seen in moment.js that is missing in the System.DateTime construct</Description>
<Copyright>(c) 2019</Copyright>
<PackageProjectUrl>https://github.com/bolorundurowb/moment.net</PackageProjectUrl>
<PackageLicenseUrl>https://github.com/bolorundurowb/moment.net/blob/master/LICENSE</PackageLicenseUrl>
<RepositoryUrl>https://github.com/bolorundurowb/moment.net</RepositoryUrl>
<RepositoryType>git</RepositoryType>
<PackageTags>moment datetime relative time</PackageTags>
<PackageReleaseNotes>First full release.</PackageReleaseNotes>
<PackageReleaseNotes>Add end time and unix timestamp support</PackageReleaseNotes>
<PackageRequireLicenseAcceptance>true</PackageRequireLicenseAcceptance>
</PropertyGroup>

Expand Down
35 changes: 35 additions & 0 deletions tests/UnixTime.Tests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
using System;
using NUnit.Framework;
using Shouldly;
using TimeZoneConverter;

namespace moment.net.Tests
{
public class UnixTimeTests
{
[Test]
public void UnixTimeInMillisecondsOneYearFromEpoch()
{
var dateTime = new DateTime(1971, 01, 01, 0, 0, 0, DateTimeKind.Utc);
var millisecondsElapsed = dateTime.UnixTimestampInMilliseconds();
millisecondsElapsed.ShouldBe(365.0 * 24 * 60 * 60 * 1000);
}

[Test]
public void UnixTimeInSecondsOneUtcYearFromEpoch()
{
var dateTime = new DateTime(1971, 01, 01, 0, 0, 0, DateTimeKind.Utc);
var secondsElapsed = dateTime.UnixTimestampInSeconds();
secondsElapsed.ShouldBe(365.0 * 24 * 60 * 60);
}

[Test]
public void UnixTimeInSecondsOneLocalYearFromEpoch()
{
var tz = TZConvert.GetTimeZoneInfo("Pacific Standard Time");
var dateTime = TimeZoneInfo.ConvertTime(new DateTime(1971, 01, 01, 8, 0, 0, DateTimeKind.Local), tz);
var secondsElapsed = dateTime.UnixTimestampInSeconds();
secondsElapsed.ShouldBe(365.0 * 24 * 60 * 60);
}
}
}
1 change: 1 addition & 0 deletions tests/moment.net.Tests.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
<PackageReference Include="NUnit3TestAdapter" Version="3.11.0" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="15.9.0" />
<PackageReference Include="Shouldly" Version="3.0.2" />
<PackageReference Include="TimeZoneConverter" Version="3.1.0" />
</ItemGroup>

<ItemGroup>
Expand Down