Skip to content

Instantly share code, notes, and snippets.

@kedzior-io
Created December 19, 2018 16:03
Show Gist options
  • Save kedzior-io/58aa95c18366b14fa8624634b4f0be1b to your computer and use it in GitHub Desktop.
Save kedzior-io/58aa95c18366b14fa8624634b4f0be1b to your computer and use it in GitHub Desktop.
Timeago razor helper for asp.net core
// Razor
// -------------------------------------------------------------------
<timeago>@comment.UtcCreatedDateTime</timeago>
// Helper
// -------------------------------------------------------------------
using Microsoft.AspNetCore.Razor.TagHelpers;
using System;
using System.Threading.Tasks;
namespace Wiyf.Web.Common.AuthoringTagHelpers
{
public class TimeagoTagHelper : TagHelper
{
public override async Task ProcessAsync(TagHelperContext context, TagHelperOutput output)
{
output.TagName = "span";
var result = string.Empty;
var content = await output.GetChildContentAsync();
if (DateTime.TryParse(content.GetContent(), out var dateTime))
{
var timeSpan = DateTime.UtcNow.Subtract(dateTime);
if (timeSpan <= TimeSpan.FromSeconds(60))
{
result = string.Format("{0} seconds ago", timeSpan.Seconds);
}
else if (timeSpan <= TimeSpan.FromMinutes(60))
{
result = timeSpan.Minutes > 1 ?
string.Format("{0} minutes ago", timeSpan.Minutes) :
"a minute ago";
}
else if (timeSpan <= TimeSpan.FromHours(24))
{
result = timeSpan.Hours > 1 ?
string.Format("{0} hours ago", timeSpan.Hours) :
"an hour ago";
}
else if (timeSpan <= TimeSpan.FromDays(30))
{
result = timeSpan.Days > 1 ?
string.Format("{0} days ago", timeSpan.Days) :
"yesterday";
}
else if (timeSpan <= TimeSpan.FromDays(365))
{
result = timeSpan.Days > 30 ?
string.Format("{0} months ago", timeSpan.Days / 30) :
"a month ago";
}
else
{
result = timeSpan.Days > 365 ?
string.Format("{0} years ago", timeSpan.Days / 365) :
"a year ago";
}
}
output.Content.SetContent(result);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment