-
-
Save rasmuseeg/c0f8f759f15906994d6c to your computer and use it in GitHub Desktop.
Inspired by moment.js
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
using System; | |
namespace System.Web | |
{ | |
public static class DateTimeExtensions { | |
#region Momentjs | |
/// <summary> | |
/// | |
/// </summary> | |
/// <param name="date"></param> | |
/// <returns>Pretty formatted date like: </returns> | |
public static string FromNow(this DateTime date) | |
{ | |
// 1. | |
// Get time span elapsed since the date. | |
TimeSpan timeElapsed = DateTime.Now.Subtract(date); | |
// 2. | |
// Get total number of days elapsed. | |
int dayDifference = (int)timeElapsed.TotalDays; | |
// 3. | |
// Get total number of seconds elapsed. | |
int secDifference = (int)timeElapsed.TotalSeconds; | |
// 4. | |
// Upcomming | |
if (dayDifference < 0) | |
{ | |
if (dayDifference == -1) | |
{ | |
// A. | |
// Greater than one minute. | |
if (secDifference > 60) | |
{ | |
return "in less than 60 seconds"; | |
} | |
// B. | |
// Greater than 2 minutes. | |
if (secDifference > 120) | |
{ | |
return "in 1 minute"; | |
} | |
// C. | |
// Greater than one hour. | |
if (secDifference > 3600) | |
{ | |
return string.Format("{0} minutes ago", | |
Math.Floor((double)secDifference / 60)); | |
} | |
// D. | |
// Greater than 2 hours. | |
if (secDifference > 7200) | |
{ | |
return "in 1 hour"; | |
} | |
// E. | |
// Greater than one day. | |
if (secDifference > 86400) | |
{ | |
return string.Format("{0} hours ago", | |
Math.Floor((double)secDifference / 3600)); | |
} | |
} | |
} else{ | |
// 5. | |
// Handle same-day times. | |
if (dayDifference == 0) | |
{ | |
// A. | |
// Less than one minute ago. | |
if (secDifference < 60) | |
{ | |
return "just now"; | |
} | |
// B. | |
// Less than 2 minutes ago. | |
if (secDifference < 120) | |
{ | |
return "1 minute ago"; | |
} | |
// C. | |
// Less than one hour ago. | |
if (secDifference < 3600) | |
{ | |
return string.Format("{0} minutes ago", | |
Math.Floor((double)secDifference / 60)); | |
} | |
// D. | |
// Less than 2 hours ago. | |
if (secDifference < 7200) | |
{ | |
return "1 hour ago"; | |
} | |
// E. | |
// Less than one day ago. | |
if (secDifference < 86400) | |
{ | |
return string.Format("{0} hours ago", | |
Math.Floor((double)secDifference / 3600)); | |
} | |
} | |
// 6. | |
// Handle previous days. | |
else if (dayDifference == 1) | |
{ | |
return "yesterday"; | |
} else if (dayDifference < 7) | |
{ | |
return string.Format("{0} days ago", | |
dayDifference); | |
} | |
if (dayDifference < 91) | |
{ | |
return string.Format("{0} week ago", | |
Math.Ceiling((double)dayDifference / 7)); | |
} | |
} | |
} | |
#endregion | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment