Skip to content

Instantly share code, notes, and snippets.

@magnusottosson
Created December 2, 2010 08:05
Show Gist options
  • Save magnusottosson/724963 to your computer and use it in GitHub Desktop.
Save magnusottosson/724963 to your computer and use it in GitHub Desktop.
Format a date to string like: "just now", "1 minute ago", "x minutes ago", "1 hour ago"...
using System;
namespace Wcm.PublicWeb.Skeleton.Wip.Campaign.Templates
{
public class PrettyDate
{
public string TextJustNow { get; set; }
public string TextOneMinuteAgo { get; set; }
public string TextMinutesAgo { get; set; }
public string TextOneHourAgo { get; set; }
public string TextHoursAgo { get; set; }
public string TextYesterDay { get; set; }
public string TextDaysAgo { get; set; }
public string TextWeeksAgo { get; set; }
public PrettyDate()
{
this.TextJustNow = "just now";
this.TextOneMinuteAgo = "1 minute ago";
this.TextMinutesAgo = "{0} minutes ago";
this.TextHoursAgo = "{0} hours ago";
this.TextOneHourAgo = "1 hour ago";
this.TextYesterDay = "yesterday";
this.TextDaysAgo = "{0} days ago";
this.TextWeeksAgo = "{0} weeks ago";
}
public string GetPrettyDate(DateTime d)
{
var s = DateTime.Now.Subtract(d);
var dayDiff = (int)s.TotalDays;
var secDiff = (int)s.TotalSeconds;
if (dayDiff == 0)
{
// Less than one minute ago.
if (secDiff < 60)
{
return this.TextJustNow;
}
// Less than 2 minutes ago.
if (secDiff < 120)
{
return this.TextOneMinuteAgo;
}
// Less than one hour ago.
if (secDiff < 3600)
{
return string.Format(this.TextMinutesAgo, Math.Floor((double)secDiff / 60));
}
// Less than 2 hours ago.
if (secDiff < 7200)
{
return this.TextOneHourAgo;
}
// Less than one day ago.
if (secDiff < 86400)
{
return string.Format(this.TextHoursAgo, Math.Floor((double)secDiff / 3600));
}
}
// Handle previous days.
if (dayDiff == 1)
{
return this.TextYesterDay;
}
if (dayDiff < 7)
{
return string.Format(this.TextDaysAgo, dayDiff);
}
return string.Format(this.TextWeeksAgo, Math.Ceiling((double)dayDiff / 7));
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment