1577

Given a specific DateTime value, how do I display relative time, like:

  • 2 hours ago
  • 3 days ago
  • a month ago
Bijender Singh Shekhawat
  • 2,707
  • 1
  • 21
  • 31
Jeff Atwood
  • 60,897
  • 45
  • 146
  • 152

39 Answers39

1036

Jeff, your code is nice but could be clearer with constants (as suggested in Code Complete).

const int SECOND = 1;
const int MINUTE = 60 * SECOND;
const int HOUR = 60 * MINUTE;
const int DAY = 24 * HOUR;
const int MONTH = 30 * DAY;

var ts = new TimeSpan(DateTime.UtcNow.Ticks - yourDate.Ticks);
double delta = Math.Abs(ts.TotalSeconds);

if (delta < 1 * MINUTE)
  return ts.Seconds == 1 ? "one second ago" : ts.Seconds + " seconds ago";

if (delta < 2 * MINUTE)
  return "a minute ago";

if (delta < 45 * MINUTE)
  return ts.Minutes + " minutes ago";

if (delta < 90 * MINUTE)
  return "an hour ago";

if (delta < 24 * HOUR)
  return ts.Hours + " hours ago";

if (delta < 48 * HOUR)
  return "yesterday";

if (delta < 30 * DAY)
  return ts.Days + " days ago";

if (delta < 12 * MONTH)
{
  int months = Convert.ToInt32(Math.Floor((double)ts.Days / 30));
  return months <= 1 ? "one month ago" : months + " months ago";
}
else
{
  int years = Convert.ToInt32(Math.Floor((double)ts.Days / 365));
  return years <= 1 ? "one year ago" : years + " years ago";
}
Community
  • 1
  • 1
Vincent Robert
  • 33,284
  • 13
  • 77
  • 115
  • 224
    I hate such constants with a passion. Does this look wrong to anyone? `Thread.Sleep(1 * MINUTE)`? Because it's wrong by a factor of 1000. – Roman Starkov Aug 17 '10 at 17:06
  • Does anyone have any guidance on how this might be implemented with a custom format string, so that `string.Format(mydate, "dd/MM/yyyy (YTT)") == "26/04/2011 (today)"? – Neil Barnwell Apr 26 '11 at 15:56
  • 37
    `const int SECOND = 1;` So weird a second is one second. – seriousdev Jun 17 '11 at 22:46
  • 2
    shouldn't be if (delta <= 90 * MINUTE) ? Somehow I got a "1 hours ago". – Roberto Jul 04 '11 at 18:06
  • 1
    When I see all capital I think back to the coding styles developed for C/C++. Microsoft's recommendation is Pascal cased. Check the answer to this question - http://stackoverflow.com/questions/242534/c-sharp-naming-convention-for-constants – CodeMonkeyKing Nov 09 '11 at 04:33
  • 66
    This type of code is nearly impossible to localize. If your app only needs to remain in English, then fine. But if you make the jump to other languages, you will hate yourself for doing logic like this. Just so y'all know... – Nik Reiman May 23 '12 at 14:31
  • 1
    @nick If you place this in an IValueConverter, it will handle the CultureInfo automatically for you (assuming you've set the culture first) – Lance McCarthy Jun 11 '12 at 20:28
  • 75
    I think if the constants were renamed to accurately describe the value that is in them, it'd be easier to understand. So SecondsPerMinute = 60; MinutesPerHour = 60; SecondsPerHour = MinutesPerHour * SecondsPerHour; etc. Just calling it MINUTE=60 doesn't allow the reader to determine what the value is. – slolife Aug 29 '12 at 16:21
  • 16
    Why nobody (except Joe) care about the wrong 'Yesterday' or 'days ago' value ??? Yesterday is not an hour calculation, but a day to day calculation. So yes, this is a wrong code at least in two frequent case. – CtrlX Sep 26 '13 at 15:47
  • 4
    @romkyns `Thread.Sleep(1 * MINUTE)` *does* look wrong to me, and it's because `MINUTE` has no units specified. Now, `MINUTE_IN_SECONDS`, that would be easy to spot and easily fixed: `Thread.Sleep(1 * MINUTE_IN_SECONDS * 1000)` or `Thread.Sleep(1 * MINUTE_IN_SECONDS * SECOND_IN_MILLISECONDS)`. (Getting verbose, but better than hidden bugs.) – jpmc26 Dec 08 '14 at 12:19
  • 1
    Another bug: Because delta is absolute, the path for "not yet" is never reached. Change to: delta = ts.TotalSeconds; – StefanG Feb 11 '15 at 12:04
  • 6
    I really don't understand why people don't use TotalMinutes, TotalDays, TotalHours... It would shorten this quite a lot... – lord.fist Feb 26 '15 at 14:23
  • 4
    The glitch is in "yesterday", it isn't quite accurate since something I am seeing today at 7 AM, that happened two days ago at 10 PM, will yield "yesterday", which isn't accurate. – Ayyash Apr 17 '15 at 06:28
  • You can optimize the solution by using the defined const on DateTime type, you have not to define them manually. – SOAL ABDELDJALLIL Apr 17 '18 at 17:26
  • Shouldn't the yourDate.Tick be an UTC time as well? ` yourDate.ToUniversalTime().Ticks – Franva Jun 09 '19 at 01:40
362

jquery.timeago plugin

Jeff, because Stack Overflow uses jQuery extensively, I recommend the jquery.timeago plugin.

Benefits:

  • Avoid timestamps dated "1 minute ago" even though the page was opened 10 minutes ago; timeago refreshes automatically.
  • You can take full advantage of page and/or fragment caching in your web applications, because the timestamps aren't calculated on the server.
  • You get to use microformats like the cool kids.

Just attach it to your timestamps on DOM ready:

jQuery(document).ready(function() {
    jQuery('abbr.timeago').timeago();
});

This will turn all abbr elements with a class of timeago and an ISO 8601 timestamp in the title:

<abbr class="timeago" title="2008-07-17T09:24:17Z">July 17, 2008</abbr>

into something like this:

<abbr class="timeago" title="July 17, 2008">4 months ago</abbr>

which yields: 4 months ago. As time passes, the timestamps will automatically update.

Disclaimer: I wrote this plugin, so I'm biased.

Kolappan N
  • 2,178
  • 2
  • 26
  • 31
Ryan McGeary
  • 221,847
  • 11
  • 90
  • 102
  • And what if the user has JavaScript disabled? jQuery (and JavaScritp generally speaking) should only be used to improve client-side experience, but your application features shouldn't depend on client technologies. You can accomplish this without using JavaScript. – Seb Mar 22 '09 at 00:27
  • 39
    Seb, If you have Javascript disabled, then the string you originally put between the abbr tags is displayed. Typically, this is just a date or time in any format you wish. Timeago degrades gracefully. It doesn't get much simpler. – Ryan McGeary Mar 24 '09 at 04:40
  • 23
    Ryan, I suggested that SO use timeago a while ago. Jeff's response made me cry, i suggest you sit down: http://stackoverflow.uservoice.com/pages/1722-general/suggestions/96770-auto-update-the-fuzzy-timestamps-with-jquery-timeago- – Rob Fonseca-Ensor Dec 26 '09 at 07:26
  • 7
    Heh, Thanks Rob. That's okay. It's barely noticeable, especially when only one number changes during the transition, though SO pages have a lot of timestamps. I would have thought he would have at least appreciated the benefits of page caching though, even if he chooses to avoid auto-updates. I'm sure Jeff could have provided feedback to improve the plugin too. I take solace knowing sites like http://arstechnica.com/ use it. – Ryan McGeary Dec 26 '09 at 13:56
  • 19
    @Rob Fonseca-Ensor - now it's making me cry too. How is an update once per minute, to show accurate information, *in any way* related to text blinking once a second? – Daniel Earwicker Apr 20 '10 at 00:23
  • 3
    An option to disable the auto-updating shouldn't be that hard, would it? If it doesn't already exist, that is... Just update the timestamps once on pageload and be done with it. – Dean Harding Apr 21 '10 at 06:43
  • 1
    @RyanMcGeary: This is probably the wrong place to ask but I have a query about using TimeAgo. I'm in the UK (GMT which includes DST) and the dates stored in my database are UTC. If I insert a date into my DB as UTC in the summertime, obviously the time will be out by 1 hour. So instead of TimeAgo printing "about 1 minute ago" it will say "about 1 hour ago". Does the TimeAgo plugin deal with the DST differences? – TheCarver Feb 14 '13 at 03:58
  • 2
    @PaparazzoKid Yes, Timeago handles time zones just fine as long as your timestamp is a proper ISO8601 timestamp. But you're right. This is the wrong place to ask this question. Go here instead: https://github.com/rmm5t/jquery-timeago/issues – Ryan McGeary Mar 31 '13 at 23:56
  • a great plugin -- just for fun i "slimmed it down" by reducing functionality, like autoupdating, and combined it with the [refactormycode answer](http://stackoverflow.com/a/79601/1037948) - http://jsfiddle.net/drzaus/eMUzF/ – drzaus Sep 26 '13 at 13:18
  • 31
    The question is about C#, I fail to see how a jQuery plugin is relevant. – BartoszKP Nov 30 '15 at 12:25
335

Here's how I do it

var ts = new TimeSpan(DateTime.UtcNow.Ticks - dt.Ticks);
double delta = Math.Abs(ts.TotalSeconds);

if (delta < 60)
{
  return ts.Seconds == 1 ? "one second ago" : ts.Seconds + " seconds ago";
}
if (delta < 60 * 2)
{
  return "a minute ago";
}
if (delta < 45 * 60)
{
  return ts.Minutes + " minutes ago";
}
if (delta < 90 * 60)
{
  return "an hour ago";
}
if (delta < 24 * 60 * 60)
{
  return ts.Hours + " hours ago";
}
if (delta < 48 * 60 * 60)
{
  return "yesterday";
}
if (delta < 30 * 24 * 60 * 60)
{
  return ts.Days + " days ago";
}
if (delta < 12 * 30 * 24 * 60 * 60)
{
  int months = Convert.ToInt32(Math.Floor((double)ts.Days / 30));
  return months <= 1 ? "one month ago" : months + " months ago";
}
int years = Convert.ToInt32(Math.Floor((double)ts.Days / 365));
return years <= 1 ? "one year ago" : years + " years ago";

Suggestions? Comments? Ways to improve this algorithm?

BlueRaja - Danny Pflughoeft
  • 75,675
  • 28
  • 177
  • 259
Jeff Atwood
  • 60,897
  • 45
  • 146
  • 152
  • 112
    "< 48*60*60s" is a rather unconventional definition for "yesterday". If it's 9am on Wednesday, would you really think of 9:01am on Monday as "yesterday". I'd have thought an algorithm for yesterday or "n days ago" should consider before/after midnight. – Joe Feb 01 '09 at 19:33
  • 140
    Compilers are usually pretty good at pre-calculating constant expressions, like 24 * 60 * 60, so you can directly use those instead of calculating it yourself to be 86400 and putting the original expression in comments – zvolkov Jun 11 '09 at 12:50
  • 11
    @bzlm I think I did for a project I was working on. My motivation here was to alert others that weeks were omitted from this code sample. As to how to do that, it seemed pretty straight forward to me. – jray Nov 09 '10 at 23:38
  • 2
    I also think this is quite a strange definition of "yesterday", if I now (sunday evening) see an answer on friday evening as "yesterday". – Paŭlo Ebermann Aug 28 '11 at 18:46
  • 9
    I think that good way to improve algorithm is displaying 2 units like "2 month 21 days ago", "1 hour 40 minutes ago" for increasing accuracy. – Evgeny Levin Feb 01 '12 at 13:42
  • 3
    Since all those If..else are just timeslabs, you can create an enum for better readability. Say `enum TimeSlabs { Seconds = 60, Minutes = 60 * 60, Hours = 60*60*24, Days = 60* 60*24*365, }` – Antony Thomas Jul 18 '12 at 17:48
  • 6
    @ Jeffy, you missed the calculation for leap year and related checks – Saboor Awan Jun 20 '13 at 05:53
  • 1
    45 minutes being displayed as "an hour ago"?! Isn't it a bug? If it isn't, why not do the same for seconds&minute? – Eldritch Conundrum Jul 24 '13 at 11:51
  • 1
    But currently SO only show the "Time ago" format until 2 days. More than 2 days and you put the standard date time format. Am I right ? – Hugo Hilário Jan 08 '14 at 10:59
  • I would just assign `var delta = ts.Duration()` so you get the absolute value in a `TimeSpan` object, and then you can do stuff like `if (delta < TimeSpan.FromMinutes(1))` or `if (delta < TimeSpan.FromDays(1))`. Still readable, and no need for cryptic numbers or constants. – Rufus L Apr 24 '18 at 04:01
93
public static string RelativeDate(DateTime theDate)
{
    Dictionary<long, string> thresholds = new Dictionary<long, string>();
    int minute = 60;
    int hour = 60 * minute;
    int day = 24 * hour;
    thresholds.Add(60, "{0} seconds ago");
    thresholds.Add(minute * 2, "a minute ago");
    thresholds.Add(45 * minute, "{0} minutes ago");
    thresholds.Add(120 * minute, "an hour ago");
    thresholds.Add(day, "{0} hours ago");
    thresholds.Add(day * 2, "yesterday");
    thresholds.Add(day * 30, "{0} days ago");
    thresholds.Add(day * 365, "{0} months ago");
    thresholds.Add(long.MaxValue, "{0} years ago");
    long since = (DateTime.Now.Ticks - theDate.Ticks) / 10000000;
    foreach (long threshold in thresholds.Keys) 
    {
        if (since < threshold) 
        {
            TimeSpan t = new TimeSpan((DateTime.Now.Ticks - theDate.Ticks));
            return string.Format(thresholds[threshold], (t.Days > 365 ? t.Days / 365 : (t.Days > 0 ? t.Days : (t.Hours > 0 ? t.Hours : (t.Minutes > 0 ? t.Minutes : (t.Seconds > 0 ? t.Seconds : 0))))).ToString());
        }
    }
    return "";
}

I prefer this version for its conciseness, and ability to add in new tick points. This could be encapsulated with a Latest() extension to Timespan instead of that long 1 liner, but for the sake of brevity in posting, this will do. This fixes the an hour ago, 1 hours ago, by providing an hour until 2 hours have elapsed

Dez
  • 5,010
  • 7
  • 37
  • 47
DevelopingChris
  • 36,999
  • 27
  • 83
  • 117
  • I am getting all sorts of problems using this function, for instance if you mock 'theDate = DateTime.Now.AddMinutes(-40);' I am getting '40 hours ago', but with Michael's refactormycode response, it returns correct at '40 minutes ago' ? – GONeale Dec 15 '08 at 02:17
  • i think you are missing a zero, try: long since = (DateTime.Now.Ticks - theDate.Ticks) / 10000000; – robnardo Aug 07 '09 at 19:37
  • 8
    Hmm, while this code may work it is incorrect and invalid to assume that the order of the keys in the Dictionary will be in a specific order. The Dictionary uses the Object.GetHashCode() which does not return a long but an int!. If you want these to be sorted then you should use a SortedList. What is wrong with the thresholds being evaluated in a set of if/else if/.../else ? You get the same number of comparisons. FYI the hash for long.MaxValue turns out to be the same as int.MinValue! – CodeMonkeyKing Nov 09 '11 at 04:47
  • OP forgot t.Days > 30 ? t.Days / 30 : – Lars Holm Jensen Oct 31 '12 at 10:39
  • To fix the issue mentioned by @CodeMonkeyKing, you could use a **`SortedDictionary`** instead of a plain `Dictionary`: The usage is the same, but it ensures that the keys are sorted. But even then, the algorithm has flaws, because `RelativeDate(DateTime.Now.AddMonths(-3).AddDays(-3))` returns **"95 months ago"**, regardless which dictionary type you're using, which is incorrect (it should return "3 months ago" or "4 months ago" depending on which threshold you're using) - even if -3 does not create a date in the past year (I have tested this in December, so in this case it should not happen). – Matt Nov 22 '16 at 12:00
70

Here a rewrite from Jeffs Script for PHP:

define("SECOND", 1);
define("MINUTE", 60 * SECOND);
define("HOUR", 60 * MINUTE);
define("DAY", 24 * HOUR);
define("MONTH", 30 * DAY);
function relativeTime($time)
{   
    $delta = time() - $time;

    if ($delta < 1 * MINUTE)
    {
        return $delta == 1 ? "one second ago" : $delta . " seconds ago";
    }
    if ($delta < 2 * MINUTE)
    {
      return "a minute ago";
    }
    if ($delta < 45 * MINUTE)
    {
        return floor($delta / MINUTE) . " minutes ago";
    }
    if ($delta < 90 * MINUTE)
    {
      return "an hour ago";
    }
    if ($delta < 24 * HOUR)
    {
      return floor($delta / HOUR) . " hours ago";
    }
    if ($delta < 48 * HOUR)
    {
      return "yesterday";
    }
    if ($delta < 30 * DAY)
    {
        return floor($delta / DAY) . " days ago";
    }
    if ($delta < 12 * MONTH)
    {
      $months = floor($delta / DAY / 30);
      return $months <= 1 ? "one month ago" : $months . " months ago";
    }
    else
    {
        $years = floor($delta / DAY / 365);
        return $years <= 1 ? "one year ago" : $years . " years ago";
    }
}    
kevinji
  • 9,983
  • 4
  • 35
  • 55
Thomaschaaf
  • 17,014
  • 31
  • 90
  • 122
68
public static string ToRelativeDate(DateTime input)
{
    TimeSpan oSpan = DateTime.Now.Subtract(input);
    double TotalMinutes = oSpan.TotalMinutes;
    string Suffix = " ago";

    if (TotalMinutes < 0.0)
    {
        TotalMinutes = Math.Abs(TotalMinutes);
        Suffix = " from now";
    }

    var aValue = new SortedList<double, Func<string>>();
    aValue.Add(0.75, () => "less than a minute");
    aValue.Add(1.5, () => "about a minute");
    aValue.Add(45, () => string.Format("{0} minutes", Math.Round(TotalMinutes)));
    aValue.Add(90, () => "about an hour");
    aValue.Add(1440, () => string.Format("about {0} hours", Math.Round(Math.Abs(oSpan.TotalHours)))); // 60 * 24
    aValue.Add(2880, () => "a day"); // 60 * 48
    aValue.Add(43200, () => string.Format("{0} days", Math.Floor(Math.Abs(oSpan.TotalDays)))); // 60 * 24 * 30
    aValue.Add(86400, () => "about a month"); // 60 * 24 * 60
    aValue.Add(525600, () => string.Format("{0} months", Math.Floor(Math.Abs(oSpan.TotalDays / 30)))); // 60 * 24 * 365 
    aValue.Add(1051200, () => "about a year"); // 60 * 24 * 365 * 2
    aValue.Add(double.MaxValue, () => string.Format("{0} years", Math.Floor(Math.Abs(oSpan.TotalDays / 365))));

    return aValue.First(n => TotalMinutes < n.Key).Value.Invoke() + Suffix;
}

http://refactormycode.com/codes/493-twitter-esque-relative-dates

C# 6 version:

static readonly SortedList<double, Func<TimeSpan, string>> offsets = 
   new SortedList<double, Func<TimeSpan, string>>
{
    { 0.75, _ => "less than a minute"},
    { 1.5, _ => "about a minute"},
    { 45, x => $"{x.TotalMinutes:F0} minutes"},
    { 90, x => "about an hour"},
    { 1440, x => $"about {x.TotalHours:F0} hours"},
    { 2880, x => "a day"},
    { 43200, x => $"{x.TotalDays:F0} days"},
    { 86400, x => "about a month"},
    { 525600, x => $"{x.TotalDays / 30:F0} months"},
    { 1051200, x => "about a year"},
    { double.MaxValue, x => $"{x.TotalDays / 365:F0} years"}
};

public static string ToRelativeDate(this DateTime input)
{
    TimeSpan x = DateTime.Now - input;
    string Suffix = x.TotalMinutes > 0 ? " ago" : " from now";
    x = new TimeSpan(Math.Abs(x.Ticks));
    return offsets.First(n => x.TotalMinutes < n.Key).Value(x) + Suffix;
}
leppie
  • 109,129
  • 16
  • 185
  • 292
  • this is very nice IMO :) This could also be refactored as an extension method? could the dictionary become static so it's only created once and referenced from then after? – Pure.Krome May 06 '09 at 12:29
  • Pure.Krome: http://stackoverflow.com/questions/11/how-do-i-calculate-relative-time/1141237#1141237 – Chris Charabaruk Jul 17 '09 at 02:48
  • 5
    You'd probably want to pull that dictionary out into a field so that you reduce instantiation and GC churn. You'd have to change `Func` to `Func`. – Drew Noakes Aug 23 '10 at 10:34
49

Here's an implementation I added as an extension method to the DateTime class that handles both future and past dates and provides an approximation option that allows you to specify the level of detail you're looking for ("3 hour ago" vs "3 hours, 23 minutes, 12 seconds ago"):

using System.Text;

/// <summary>
/// Compares a supplied date to the current date and generates a friendly English 
/// comparison ("5 days ago", "5 days from now")
/// </summary>
/// <param name="date">The date to convert</param>
/// <param name="approximate">When off, calculate timespan down to the second.
/// When on, approximate to the largest round unit of time.</param>
/// <returns></returns>
public static string ToRelativeDateString(this DateTime value, bool approximate)
{
    StringBuilder sb = new StringBuilder();

    string suffix = (value > DateTime.Now) ? " from now" : " ago";

    TimeSpan timeSpan = new TimeSpan(Math.Abs(DateTime.Now.Subtract(value).Ticks));

    if (timeSpan.Days > 0)
    {
        sb.AppendFormat("{0} {1}", timeSpan.Days,
          (timeSpan.Days > 1) ? "days" : "day");
        if (approximate) return sb.ToString() + suffix;
    }
    if (timeSpan.Hours > 0)
    {
        sb.AppendFormat("{0}{1} {2}", (sb.Length > 0) ? ", " : string.Empty,
          timeSpan.Hours, (timeSpan.Hours > 1) ? "hours" : "hour");
        if (approximate) return sb.ToString() + suffix;
    }
    if (timeSpan.Minutes > 0)
    {
        sb.AppendFormat("{0}{1} {2}", (sb.Length > 0) ? ", " : string.Empty, 
          timeSpan.Minutes, (timeSpan.Minutes > 1) ? "minutes" : "minute");
        if (approximate) return sb.ToString() + suffix;
    }
    if (timeSpan.Seconds > 0)
    {
        sb.AppendFormat("{0}{1} {2}", (sb.Length > 0) ? ", " : string.Empty, 
          timeSpan.Seconds, (timeSpan.Seconds > 1) ? "seconds" : "second");
        if (approximate) return sb.ToString() + suffix;
    }
    if (sb.Length == 0) return "right now";

    sb.Append(suffix);
    return sb.ToString();
}
Ionică Bizău
  • 93,552
  • 74
  • 254
  • 426
neuracnu
  • 109
  • 3
  • 7
38

There are also a package called Humanizr on Nuget, and it actually works really well, and is in the .NET Foundation.

DateTime.UtcNow.AddHours(-30).Humanize() => "yesterday"
DateTime.UtcNow.AddHours(-2).Humanize() => "2 hours ago"

DateTime.UtcNow.AddHours(30).Humanize() => "tomorrow"
DateTime.UtcNow.AddHours(2).Humanize() => "2 hours from now"

TimeSpan.FromMilliseconds(1299630020).Humanize() => "2 weeks"
TimeSpan.FromMilliseconds(1299630020).Humanize(3) => "2 weeks, 1 day, 1 hour"

Scott Hanselman has a writeup on it on his blog

Shimmy Weitzhandler
  • 92,920
  • 119
  • 388
  • 596
Karl-Henrik
  • 1,087
  • 1
  • 11
  • 17
  • 3
    friendly note: On .net 4.5 or above don't install complete Humanizer... only install Humanizer.Core part of it.. cause other language packages are not supported on this version – Ahmad Mar 10 '17 at 18:50
36

I would recommend computing this on the client side too. Less work for the server.

The following is the version that I use (from Zach Leatherman)

/*
 * Javascript Humane Dates
 * Copyright (c) 2008 Dean Landolt (deanlandolt.com)
 * Re-write by Zach Leatherman (zachleat.com)
 * 
 * Adopted from the John Resig's pretty.js
 * at http://ejohn.org/blog/javascript-pretty-date
 * and henrah's proposed modification 
 * at http://ejohn.org/blog/javascript-pretty-date/#comment-297458
 * 
 * Licensed under the MIT license.
 */

function humane_date(date_str){
        var time_formats = [
                [60, 'just now'],
                [90, '1 minute'], // 60*1.5
                [3600, 'minutes', 60], // 60*60, 60
                [5400, '1 hour'], // 60*60*1.5
                [86400, 'hours', 3600], // 60*60*24, 60*60
                [129600, '1 day'], // 60*60*24*1.5
                [604800, 'days', 86400], // 60*60*24*7, 60*60*24
                [907200, '1 week'], // 60*60*24*7*1.5
                [2628000, 'weeks', 604800], // 60*60*24*(365/12), 60*60*24*7
                [3942000, '1 month'], // 60*60*24*(365/12)*1.5
                [31536000, 'months', 2628000], // 60*60*24*365, 60*60*24*(365/12)
                [47304000, '1 year'], // 60*60*24*365*1.5
                [3153600000, 'years', 31536000], // 60*60*24*365*100, 60*60*24*365
                [4730400000, '1 century'] // 60*60*24*365*100*1.5
        ];

        var time = ('' + date_str).replace(/-/g,"/").replace(/[TZ]/g," "),
                dt = new Date,
                seconds = ((dt - new Date(time) + (dt.getTimezoneOffset() * 60000)) / 1000),
                token = ' ago',
                i = 0,
                format;

        if (seconds < 0) {
                seconds = Math.abs(seconds);
                token = '';
        }

        while (format = time_formats[i++]) {
                if (seconds < format[0]) {
                        if (format.length == 2) {
                                return format[1] + (i > 1 ? token : ''); // Conditional so we don't return Just Now Ago
                        } else {
                                return Math.round(seconds / format[2]) + ' ' + format[1] + (i > 1 ? token : '');
                        }
                }
        }

        // overflow for centuries
        if(seconds > 4730400000)
                return Math.round(seconds / 4730400000) + ' centuries' + token;

        return date_str;
};

if(typeof jQuery != 'undefined') {
        jQuery.fn.humane_dates = function(){
                return this.each(function(){
                        var date = humane_date(this.title);
                        if(date && jQuery(this).text() != date) // don't modify the dom if we don't have to
                                jQuery(this).text(date);
                });
        };
}
Ionică Bizău
  • 93,552
  • 74
  • 254
  • 426
Jauder Ho
  • 1,305
  • 1
  • 16
  • 22
31

@jeff

IMHO yours seems a little long. However it does seem a little more robust with support for "yesterday" and "years". But in my experience when this is used, the person is most likely to view the content in the first 30 days. It is only the really hardcore people that come after that. So, I usually elect to keep this short and simple.

This is the method I am currently using in one of my websites. This returns only a relative day, hour and time. And then the user has to slap on "ago" in the output.

public static string ToLongString(this TimeSpan time)
{
    string output = String.Empty;

    if (time.Days > 0)
        output += time.Days + " days ";

    if ((time.Days == 0 || time.Days == 1) && time.Hours > 0)
        output += time.Hours + " hr ";

    if (time.Days == 0 && time.Minutes > 0)
        output += time.Minutes + " min ";

    if (output.Length == 0)
        output += time.Seconds + " sec";

    return output.Trim();
}
Tanjim Khan
  • 556
  • 1
  • 7
  • 17
Nick Berardi
  • 52,504
  • 14
  • 109
  • 135
25

A couple of years late to the party, but I had a requirement to do this for both past and future dates, so I combined Jeff's and Vincent's into this. It's a ternarytastic extravaganza! :)

public static class DateTimeHelper
    {
        private const int SECOND = 1;
        private const int MINUTE = 60 * SECOND;
        private const int HOUR = 60 * MINUTE;
        private const int DAY = 24 * HOUR;
        private const int MONTH = 30 * DAY;

        /// <summary>
        /// Returns a friendly version of the provided DateTime, relative to now. E.g.: "2 days ago", or "in 6 months".
        /// </summary>
        /// <param name="dateTime">The DateTime to compare to Now</param>
        /// <returns>A friendly string</returns>
        public static string GetFriendlyRelativeTime(DateTime dateTime)
        {
            if (DateTime.UtcNow.Ticks == dateTime.Ticks)
            {
                return "Right now!";
            }

            bool isFuture = (DateTime.UtcNow.Ticks < dateTime.Ticks);
            var ts = DateTime.UtcNow.Ticks < dateTime.Ticks ? new TimeSpan(dateTime.Ticks - DateTime.UtcNow.Ticks) : new TimeSpan(DateTime.UtcNow.Ticks - dateTime.Ticks);

            double delta = ts.TotalSeconds;

            if (delta < 1 * MINUTE)
            {
                return isFuture ? "in " + (ts.Seconds == 1 ? "one second" : ts.Seconds + " seconds") : ts.Seconds == 1 ? "one second ago" : ts.Seconds + " seconds ago";
            }
            if (delta < 2 * MINUTE)
            {
                return isFuture ? "in a minute" : "a minute ago";
            }
            if (delta < 45 * MINUTE)
            {
                return isFuture ? "in " + ts.Minutes + " minutes" : ts.Minutes + " minutes ago";
            }
            if (delta < 90 * MINUTE)
            {
                return isFuture ? "in an hour" : "an hour ago";
            }
            if (delta < 24 * HOUR)
            {
                return isFuture ? "in " + ts.Hours + " hours" : ts.Hours + " hours ago";
            }
            if (delta < 48 * HOUR)
            {
                return isFuture ? "tomorrow" : "yesterday";
            }
            if (delta < 30 * DAY)
            {
                return isFuture ? "in " + ts.Days + " days" : ts.Days + " days ago";
            }
            if (delta < 12 * MONTH)
            {
                int months = Convert.ToInt32(Math.Floor((double)ts.Days / 30));
                return isFuture ? "in " + (months <= 1 ? "one month" : months + " months") : months <= 1 ? "one month ago" : months + " months ago";
            }
            else
            {
                int years = Convert.ToInt32(Math.Floor((double)ts.Days / 365));
                return isFuture ? "in " + (years <= 1 ? "one year" : years + " years") : years <= 1 ? "one year ago" : years + " years ago";
            }
        }
    }
Community
  • 1
  • 1
Town
  • 14,143
  • 3
  • 47
  • 71
21

Is there an easy way to do this in Java? The java.util.Date class seems rather limited.

Here is my quick and dirty Java solution:

import java.util.Date;
import javax.management.timer.Timer;

String getRelativeDate(Date date) {     
  long delta = new Date().getTime() - date.getTime();
  if (delta < 1L * Timer.ONE_MINUTE) {
    return toSeconds(delta) == 1 ? "one second ago" : toSeconds(delta) + " seconds ago";
  }
  if (delta < 2L * Timer.ONE_MINUTE) {
    return "a minute ago";
  }
  if (delta < 45L * Timer.ONE_MINUTE) {
    return toMinutes(delta) + " minutes ago";
  }
  if (delta < 90L * Timer.ONE_MINUTE) {
    return "an hour ago";
  }
  if (delta < 24L * Timer.ONE_HOUR) {
    return toHours(delta) + " hours ago";
  }
  if (delta < 48L * Timer.ONE_HOUR) {
    return "yesterday";
  }
  if (delta < 30L * Timer.ONE_DAY) {
    return toDays(delta) + " days ago";
  }
  if (delta < 12L * 4L * Timer.ONE_WEEK) { // a month
    long months = toMonths(delta); 
    return months <= 1 ? "one month ago" : months + " months ago";
  }
  else {
    long years = toYears(delta);
    return years <= 1 ? "one year ago" : years + " years ago";
  }
}

private long toSeconds(long date) {
  return date / 1000L;
}

private long toMinutes(long date) {
  return toSeconds(date) / 60L;
}

private long toHours(long date) {
  return toMinutes(date) / 60L;
}

private long toDays(long date) {
  return toHours(date) / 24L;
}

private long toMonths(long date) {
  return toDays(date) / 30L;
}

private long toYears(long date) {
  return toMonths(date) / 365L;
}
Bhushan
  • 6,017
  • 12
  • 54
  • 89
20

iPhone Objective-C Version

+ (NSString *)timeAgoString:(NSDate *)date {
    int delta = -(int)[date timeIntervalSinceNow];

    if (delta < 60)
    {
        return delta == 1 ? @"one second ago" : [NSString stringWithFormat:@"%i seconds ago", delta];
    }
    if (delta < 120)
    {
        return @"a minute ago";
    }
    if (delta < 2700)
    {
        return [NSString stringWithFormat:@"%i minutes ago", delta/60];
    }
    if (delta < 5400)
    {
        return @"an hour ago";
    }
    if (delta < 24 * 3600)
    {
        return [NSString stringWithFormat:@"%i hours ago", delta/3600];
    }
    if (delta < 48 * 3600)
    {
        return @"yesterday";
    }
    if (delta < 30 * 24 * 3600)
    {
        return [NSString stringWithFormat:@"%i days ago", delta/(24*3600)];
    }
    if (delta < 12 * 30 * 24 * 3600)
    {
        int months = delta/(30*24*3600);
        return months <= 1 ? @"one month ago" : [NSString stringWithFormat:@"%i months ago", months];
    }
    else
    {
        int years = delta/(12*30*24*3600);
        return years <= 1 ? @"one year ago" : [NSString stringWithFormat:@"%i years ago", years];
    }
}
a stone arachnid
  • 1,212
  • 1
  • 13
  • 24
0llie
  • 8,430
  • 2
  • 18
  • 10
20

Given the world and her husband appear to be posting code samples, here is what I wrote a while ago, based on a couple of these answers.

I had a specific need for this code to be localisable. So I have two classes — Grammar, which specifies the localisable terms, and FuzzyDateExtensions, which holds a bunch of extension methods. I had no need to deal with future datetimes, so no attempt is made to handle them with this code.

I've left some of the XMLdoc in the source, but removed most (where they'd be obvious) for brevity's sake. I've also not included every class member here:

public class Grammar
{
    /// <summary> Gets or sets the term for "just now". </summary>
    public string JustNow { get; set; }
    /// <summary> Gets or sets the term for "X minutes ago". </summary>
    /// <remarks>
    ///     This is a <see cref="String.Format"/> pattern, where <c>{0}</c>
    ///     is the number of minutes.
    /// </remarks>
    public string MinutesAgo { get; set; }
    public string OneHourAgo { get; set; }
    public string HoursAgo { get; set; }
    public string Yesterday { get; set; }
    public string DaysAgo { get; set; }
    public string LastMonth { get; set; }
    public string MonthsAgo { get; set; }
    public string LastYear { get; set; }
    public string YearsAgo { get; set; }
    /// <summary> Gets or sets the term for "ages ago". </summary>
    public string AgesAgo { get; set; }

    /// <summary>
    ///     Gets or sets the threshold beyond which the fuzzy date should be
    ///     considered "ages ago".
    /// </summary>
    public TimeSpan AgesAgoThreshold { get; set; }

    /// <summary>
    ///     Initialises a new <see cref="Grammar"/> instance with the
    ///     specified properties.
    /// </summary>
    private void Initialise(string justNow, string minutesAgo,
        string oneHourAgo, string hoursAgo, string yesterday, string daysAgo,
        string lastMonth, string monthsAgo, string lastYear, string yearsAgo,
        string agesAgo, TimeSpan agesAgoThreshold)
    { ... }
}

The FuzzyDateString class contains:

public static class FuzzyDateExtensions
{
    public static string ToFuzzyDateString(this TimeSpan timespan)
    {
        return timespan.ToFuzzyDateString(new Grammar());
    }

    public static string ToFuzzyDateString(this TimeSpan timespan,
        Grammar grammar)
    {
        return GetFuzzyDateString(timespan, grammar);
    }

    public static string ToFuzzyDateString(this DateTime datetime)
    {
        return (DateTime.Now - datetime).ToFuzzyDateString();
    }

    public static string ToFuzzyDateString(this DateTime datetime,
       Grammar grammar)
    {
        return (DateTime.Now - datetime).ToFuzzyDateString(grammar);
    }


    private static string GetFuzzyDateString(TimeSpan timespan,
       Grammar grammar)
    {
        timespan = timespan.Duration();

        if (timespan >= grammar.AgesAgoThreshold)
        {
            return grammar.AgesAgo;
        }

        if (timespan < new TimeSpan(0, 2, 0))    // 2 minutes
        {
            return grammar.JustNow;
        }

        if (timespan < new TimeSpan(1, 0, 0))    // 1 hour
        {
            return String.Format(grammar.MinutesAgo, timespan.Minutes);
        }

        if (timespan < new TimeSpan(1, 55, 0))    // 1 hour 55 minutes
        {
            return grammar.OneHourAgo;
        }

        if (timespan < new TimeSpan(12, 0, 0)    // 12 hours
            && (DateTime.Now - timespan).IsToday())
        {
            return String.Format(grammar.HoursAgo, timespan.RoundedHours());
        }

        if ((DateTime.Now.AddDays(1) - timespan).IsToday())
        {
            return grammar.Yesterday;
        }

        if (timespan < new TimeSpan(32, 0, 0, 0)    // 32 days
            && (DateTime.Now - timespan).IsThisMonth())
        {
            return String.Format(grammar.DaysAgo, timespan.RoundedDays());
        }

        if ((DateTime.Now.AddMonths(1) - timespan).IsThisMonth())
        {
            return grammar.LastMonth;
        }

        if (timespan < new TimeSpan(365, 0, 0, 0, 0)    // 365 days
            && (DateTime.Now - timespan).IsThisYear())
        {
            return String.Format(grammar.MonthsAgo, timespan.RoundedMonths());
        }

        if ((DateTime.Now - timespan).AddYears(1).IsThisYear())
        {
            return grammar.LastYear;
        }

        return String.Format(grammar.YearsAgo, timespan.RoundedYears());
    }
}

One of the key things I wanted to achieve, as well as localisation, was that "today" would only mean "this calendar day", so the IsToday, IsThisMonth, IsThisYear methods look like this:

public static bool IsToday(this DateTime date)
{
    return date.DayOfYear == DateTime.Now.DayOfYear && date.IsThisYear();
}

and the rounding methods are like this (I've included RoundedMonths, as that's a bit different):

public static int RoundedDays(this TimeSpan timespan)
{
    return (timespan.Hours > 12) ? timespan.Days + 1 : timespan.Days;
}

public static int RoundedMonths(this TimeSpan timespan)
{
    DateTime then = DateTime.Now - timespan;

    // Number of partial months elapsed since 1 Jan, AD 1 (DateTime.MinValue)
    int nowMonthYears = DateTime.Now.Year * 12 + DateTime.Now.Month;
    int thenMonthYears = then.Year * 12 + then.Month;                    

    return nowMonthYears - thenMonthYears;
}

I hope people find this useful and/or interesting :o)

Dez
  • 5,010
  • 7
  • 37
  • 47
Owen Blacker
  • 3,889
  • 2
  • 33
  • 68
18

using Fluent DateTime

var dateTime1 = 2.Hours().Ago();
var dateTime2 = 3.Days().Ago();
var dateTime3 = 1.Months().Ago();
var dateTime4 = 5.Hours().FromNow();
var dateTime5 = 2.Weeks().FromNow();
var dateTime6 = 40.Seconds().FromNow();
Kolappan N
  • 2,178
  • 2
  • 26
  • 31
Simon
  • 30,844
  • 15
  • 120
  • 187
17

In PHP, I do it this way:

<?php
function timesince($original) {
    // array of time period chunks
    $chunks = array(
        array(60 * 60 * 24 * 365 , 'year'),
        array(60 * 60 * 24 * 30 , 'month'),
        array(60 * 60 * 24 * 7, 'week'),
        array(60 * 60 * 24 , 'day'),
        array(60 * 60 , 'hour'),
        array(60 , 'minute'),
    );

    $today = time(); /* Current unix time  */
    $since = $today - $original;

    if($since > 604800) {
    $print = date("M jS", $original);

    if($since > 31536000) {
        $print .= ", " . date("Y", $original);
    }

    return $print;
}

// $j saves performing the count function each time around the loop
for ($i = 0, $j = count($chunks); $i < $j; $i++) {

    $seconds = $chunks[$i][0];
    $name = $chunks[$i][1];

    // finding the biggest chunk (if the chunk fits, break)
    if (($count = floor($since / $seconds)) != 0) {
        break;
    }
}

$print = ($count == 1) ? '1 '.$name : "$count {$name}s";

return $print . " ago";

} ?>
kevinji
  • 9,983
  • 4
  • 35
  • 55
icco
  • 3,024
  • 4
  • 32
  • 46
15

I thought I'd give this a shot using classes and polymorphism. I had a previous iteration which used sub-classing which ended up having way too much overhead. I've switched to a more flexible delegate / public property object model which is significantly better. My code is very slightly more accurate, I wish I could come up with a better way to generate "months ago" that didn't seem too over-engineered.

I think I'd still stick with Jeff's if-then cascade because it's less code and it's simpler (it's definitely easier to ensure it'll work as expected).

For the below code PrintRelativeTime.GetRelativeTimeMessage(TimeSpan ago) returns the relative time message (e.g. "yesterday").

public class RelativeTimeRange : IComparable
{
    public TimeSpan UpperBound { get; set; }

    public delegate string RelativeTimeTextDelegate(TimeSpan timeDelta);

    public RelativeTimeTextDelegate MessageCreator { get; set; }

    public int CompareTo(object obj)
    {
        if (!(obj is RelativeTimeRange))
        {
            return 1;
        }
        // note that this sorts in reverse order to the way you'd expect, 
        // this saves having to reverse a list later
        return (obj as RelativeTimeRange).UpperBound.CompareTo(UpperBound);
    }
}

public class PrintRelativeTime
{
    private static List<RelativeTimeRange> timeRanges;

    static PrintRelativeTime()
    {
        timeRanges = new List<RelativeTimeRange>{
            new RelativeTimeRange
            {
                UpperBound = TimeSpan.FromSeconds(1),
                MessageCreator = (delta) => 
                { return "one second ago"; }
            }, 
            new RelativeTimeRange
            {
                UpperBound = TimeSpan.FromSeconds(60),
                MessageCreator = (delta) => 
                { return delta.Seconds + " seconds ago"; }

            }, 
            new RelativeTimeRange
            {
                UpperBound = TimeSpan.FromMinutes(2),
                MessageCreator = (delta) => 
                { return "one minute ago"; }
            }, 
            new RelativeTimeRange
            {
                UpperBound = TimeSpan.FromMinutes(60),
                MessageCreator = (delta) => 
                { return delta.Minutes + " minutes ago"; }
            }, 
            new RelativeTimeRange
            {
                UpperBound = TimeSpan.FromHours(2),
                MessageCreator = (delta) => 
                { return "one hour ago"; }
            }, 
            new RelativeTimeRange
            {
                UpperBound = TimeSpan.FromHours(24),
                MessageCreator = (delta) => 
                { return delta.Hours + " hours ago"; }
            }, 
            new RelativeTimeRange
            {
                UpperBound = TimeSpan.FromDays(2),
                MessageCreator = (delta) => 
                { return "yesterday"; }
            }, 
            new RelativeTimeRange
            {
                UpperBound = DateTime.Now.Subtract(DateTime.Now.AddMonths(-1)),
                MessageCreator = (delta) => 
                { return delta.Days + " days ago"; }
            }, 
            new RelativeTimeRange
            {
                UpperBound = DateTime.Now.Subtract(DateTime.Now.AddMonths(-2)),
                MessageCreator = (delta) => 
                { return "one month ago"; }
            }, 
            new RelativeTimeRange
            {
                UpperBound = DateTime.Now.Subtract(DateTime.Now.AddYears(-1)),
                MessageCreator = (delta) => 
                { return (int)Math.Floor(delta.TotalDays / 30) + " months ago"; }
            }, 
            new RelativeTimeRange
            {
                UpperBound = DateTime.Now.Subtract(DateTime.Now.AddYears(-2)),
                MessageCreator = (delta) => 
                { return "one year ago"; }
            }, 
            new RelativeTimeRange
            {
                UpperBound = TimeSpan.MaxValue,
                MessageCreator = (delta) => 
                { return (int)Math.Floor(delta.TotalDays / 365.24D) + " years ago"; }
            }
        };

        timeRanges.Sort();
    }

    public static string GetRelativeTimeMessage(TimeSpan ago)
    {
        RelativeTimeRange postRelativeDateRange = timeRanges[0];

        foreach (var timeRange in timeRanges)
        {
            if (ago.CompareTo(timeRange.UpperBound) <= 0)
            {
                postRelativeDateRange = timeRange;
            }
        }

        return postRelativeDateRange.MessageCreator(ago);
    }
}
Wedge
  • 18,614
  • 7
  • 44
  • 69
13
using System;
using System.Collections.Generic;
using System.Linq;

public static class RelativeDateHelper
{
    private static Dictionary<double, Func<double, string>> sm_Dict = null;

    private static Dictionary<double, Func<double, string>> DictionarySetup()
    {
        var dict = new Dictionary<double, Func<double, string>>();
        dict.Add(0.75, (mins) => "less than a minute");
        dict.Add(1.5, (mins) => "about a minute");
        dict.Add(45, (mins) => string.Format("{0} minutes", Math.Round(mins)));
        dict.Add(90, (mins) => "about an hour");
        dict.Add(1440, (mins) => string.Format("about {0} hours", Math.Round(Math.Abs(mins / 60)))); // 60 * 24
        dict.Add(2880, (mins) => "a day"); // 60 * 48
        dict.Add(43200, (mins) => string.Format("{0} days", Math.Floor(Math.Abs(mins / 1440)))); // 60 * 24 * 30
        dict.Add(86400, (mins) => "about a month"); // 60 * 24 * 60
        dict.Add(525600, (mins) => string.Format("{0} months", Math.Floor(Math.Abs(mins / 43200)))); // 60 * 24 * 365 
        dict.Add(1051200, (mins) => "about a year"); // 60 * 24 * 365 * 2
        dict.Add(double.MaxValue, (mins) => string.Format("{0} years", Math.Floor(Math.Abs(mins / 525600))));

        return dict;
    }

    public static string ToRelativeDate(this DateTime input)
    {
        TimeSpan oSpan = DateTime.Now.Subtract(input);
        double TotalMinutes = oSpan.TotalMinutes;
        string Suffix = " ago";

        if (TotalMinutes < 0.0)
        {
            TotalMinutes = Math.Abs(TotalMinutes);
            Suffix = " from now";
        }

        if (null == sm_Dict)
            sm_Dict = DictionarySetup();

        return sm_Dict.First(n => TotalMinutes < n.Key).Value.Invoke(TotalMinutes) + Suffix;
    }
}

The same as another answer to this question but as an extension method with a static dictionary.

Community
  • 1
  • 1
Chris Charabaruk
  • 4,267
  • 2
  • 26
  • 57
  • What does the dictionary buy you here? – StriplingWarrior May 26 '11 at 21:46
  • StriplingWarrior: Ease of reading and modifying compared to a switch statement or a stack of if/else statements. The dictionary being static means that it and the Func objects don't have to be created every time we want to use ToRelativeDate; it's created only once, compared to the one I linked in my answer. – Chris Charabaruk May 31 '11 at 04:42
  • I see. I was just thinking, since the documentation on `Dictionary` states that "The order in which the items are returned is undefined," (http://msdn.microsoft.com/en-us/library/xfhwa508.aspx) perhaps that's not the best data structure to use when you don't care about lookup times as much as having things stay in order. – StriplingWarrior May 31 '11 at 16:00
  • StriplingWarrior: I believe LINQ takes that into account when used with `Dictionary`s. If you're still uncomfortable with it, you can use [`SortedDictionary`](http://msdn.microsoft.com/en-us/library/f7fta44c.aspx), but my own experience shows that to be unnecessary. – Chris Charabaruk Jun 01 '11 at 02:44
13

When you know the viewer's time zone, it might be clearer to use calendar days at the day scale. I'm not familiar with the .NET libraries so I don't know how you'd do that in C#, unfortunately.

On consumer sites, you could also be hand-wavier under a minute. "Less than a minute ago" or "just now" could be good enough.

markpasc
  • 863
  • 8
  • 13
11

you can try this.I think it will work correctly.

long delta = new Date().getTime() - date.getTime();
const int SECOND = 1;
const int MINUTE = 60 * SECOND;
const int HOUR = 60 * MINUTE;
const int DAY = 24 * HOUR;
const int MONTH = 30 * DAY;

if (delta < 0L)
{
  return "not yet";
}
if (delta < 1L * MINUTE)
{
  return ts.Seconds == 1 ? "one second ago" : ts.Seconds + " seconds ago";
}
if (delta < 2L * MINUTE)
{
  return "a minute ago";
}
if (delta < 45L * MINUTE)
{
  return ts.Minutes + " minutes ago";
}
if (delta < 90L * MINUTE)
{
  return "an hour ago";
}
if (delta < 24L * HOUR)
{
  return ts.Hours + " hours ago";
}
if (delta < 48L * HOUR)
{
  return "yesterday";
}
if (delta < 30L * DAY)
{
  return ts.Days + " days ago";
}
if (delta < 12L * MONTH)
{
  int months = Convert.ToInt32(Math.Floor((double)ts.Days / 30));
  return months <= 1 ? "one month ago" : months + " months ago";
}
else
{
  int years = Convert.ToInt32(Math.Floor((double)ts.Days / 365));
  return years <= 1 ? "one year ago" : years + " years ago";
}
Premdeep Mohanty
  • 751
  • 5
  • 10
10

@Jeff

var ts = new TimeSpan(DateTime.UtcNow.Ticks - dt.Ticks);

Doing a subtraction on DateTime returns a TimeSpan anyway.

So you can just do

(DateTime.UtcNow - dt).TotalSeconds

I'm also surprised to see the constants multiplied-out by hand and then comments added with the multiplications in. Was that some misguided optimisation?

a stone arachnid
  • 1,212
  • 1
  • 13
  • 24
Will Dean
  • 37,648
  • 10
  • 84
  • 116
9

Here's the algorithm stackoverflow uses but rewritten more concisely in perlish pseudocode with a bug fix (no "one hours ago"). The function takes a (positive) number of seconds ago and returns a human-friendly string like "3 hours ago" or "yesterday".

agoify($delta)
  local($y, $mo, $d, $h, $m, $s);
  $s = floor($delta);
  if($s<=1)            return "a second ago";
  if($s<60)            return "$s seconds ago";
  $m = floor($s/60);
  if($m==1)            return "a minute ago";
  if($m<45)            return "$m minutes ago";
  $h = floor($m/60);
  if($h==1)            return "an hour ago";
  if($h<24)            return "$h hours ago";
  $d = floor($h/24);
  if($d<2)             return "yesterday";
  if($d<30)            return "$d days ago";
  $mo = floor($d/30);
  if($mo<=1)           return "a month ago";
  $y = floor($mo/12);
  if($y<1)             return "$mo months ago";
  if($y==1)            return "a year ago";
  return "$y years ago";
dreeves
  • 25,132
  • 42
  • 147
  • 226
9

You can reduce the server-side load by performing this logic client-side. View source on some Digg pages for reference. They have the server emit an epoch time value that gets processed by Javascript. This way you don't need to manage the end user's time zone. The new server-side code would be something like:

public string GetRelativeTime(DateTime timeStamp)
{
    return string.Format("<script>printdate({0});</script>", timeStamp.ToFileTimeUtc());
}

You could even add a NOSCRIPT block there and just perform a ToString().

Kolappan N
  • 2,178
  • 2
  • 26
  • 31
9

Java for client-side gwt usage:

import java.util.Date;

public class RelativeDateFormat {

 private static final long ONE_MINUTE = 60000L;
 private static final long ONE_HOUR = 3600000L;
 private static final long ONE_DAY = 86400000L;
 private static final long ONE_WEEK = 604800000L;

 public static String format(Date date) {

  long delta = new Date().getTime() - date.getTime();
  if (delta < 1L * ONE_MINUTE) {
   return toSeconds(delta) == 1 ? "one second ago" : toSeconds(delta)
     + " seconds ago";
  }
  if (delta < 2L * ONE_MINUTE) {
   return "one minute ago";
  }
  if (delta < 45L * ONE_MINUTE) {
   return toMinutes(delta) + " minutes ago";
  }
  if (delta < 90L * ONE_MINUTE) {
   return "one hour ago";
  }
  if (delta < 24L * ONE_HOUR) {
   return toHours(delta) + " hours ago";
  }
  if (delta < 48L * ONE_HOUR) {
   return "yesterday";
  }
  if (delta < 30L * ONE_DAY) {
   return toDays(delta) + " days ago";
  }
  if (delta < 12L * 4L * ONE_WEEK) {
   long months = toMonths(delta);
   return months <= 1 ? "one month ago" : months + " months ago";
  } else {
   long years = toYears(delta);
   return years <= 1 ? "one year ago" : years + " years ago";
  }
 }

 private static long toSeconds(long date) {
  return date / 1000L;
 }

 private static long toMinutes(long date) {
  return toSeconds(date) / 60L;
 }

 private static long toHours(long date) {
  return toMinutes(date) / 60L;
 }

 private static long toDays(long date) {
  return toHours(date) / 24L;
 }

 private static long toMonths(long date) {
  return toDays(date) / 30L;
 }

 private static long toYears(long date) {
  return toMonths(date) / 365L;
 }

}
antony.trupe
  • 10,028
  • 10
  • 54
  • 81
9

You can use TimeAgo extension as below:

public static string TimeAgo(this DateTime dateTime)
{
    string result = string.Empty;
    var timeSpan = DateTime.Now.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("about {0} minutes ago", timeSpan.Minutes) :
            "about a minute ago";
    }
    else if (timeSpan <= TimeSpan.FromHours(24))
    {
        result = timeSpan.Hours > 1 ? 
            String.Format("about {0} hours ago", timeSpan.Hours) : 
            "about an hour ago";
    }
    else if (timeSpan <= TimeSpan.FromDays(30))
    {
        result = timeSpan.Days > 1 ? 
            String.Format("about {0} days ago", timeSpan.Days) : 
            "yesterday";
    }
    else if (timeSpan <= TimeSpan.FromDays(365))
    {
        result = timeSpan.Days > 30 ? 
            String.Format("about {0} months ago", timeSpan.Days / 30) : 
            "about a month ago";
    }
    else
    {
        result = timeSpan.Days > 365 ? 
            String.Format("about {0} years ago", timeSpan.Days / 365) : 
            "about a year ago";
    }
 
    return result;
}

Or use jQuery plugin with Razor extension from Timeago.

Tanjim Khan
  • 556
  • 1
  • 7
  • 17
Piotr Stapp
  • 18,130
  • 10
  • 63
  • 104
8

I got this answer from one of Bill Gates' blogs. I need to find it on my browser history and I'll give you the link.

The Javascript code to do the same thing (as requested):

function posted(t) {
    var now = new Date();
    var diff = parseInt((now.getTime() - Date.parse(t)) / 1000);
    if (diff < 60) { return 'less than a minute ago'; }
    else if (diff < 120) { return 'about a minute ago'; }
    else if (diff < (2700)) { return (parseInt(diff / 60)).toString() + ' minutes ago'; }
    else if (diff < (5400)) { return 'about an hour ago'; }
    else if (diff < (86400)) { return 'about ' + (parseInt(diff / 3600)).toString() + ' hours ago'; }
    else if (diff < (172800)) { return '1 day ago'; } 
    else {return (parseInt(diff / 86400)).toString() + ' days ago'; }
}

Basically, you work in terms of seconds.

Tanjim Khan
  • 556
  • 1
  • 7
  • 17
Buhake Sindi
  • 82,658
  • 26
  • 157
  • 220
6

I think there is already a number of answers related to this post, but one can use this which is easy to use just like plugin and also easily readable for programmers. Send your specific date, and get its value in string form:

public string RelativeDateTimeCount(DateTime inputDateTime)
{
    string outputDateTime = string.Empty;
    TimeSpan ts = DateTime.Now - inputDateTime;

    if (ts.Days > 7)
    { outputDateTime = inputDateTime.ToString("MMMM d, yyyy"); }

    else if (ts.Days > 0)
    {
        outputDateTime = ts.Days == 1 ? ("about 1 Day ago") : ("about " + ts.Days.ToString() + " Days ago");
    }
    else if (ts.Hours > 0)
    {
        outputDateTime = ts.Hours == 1 ? ("an hour ago") : (ts.Hours.ToString() + " hours ago");
    }
    else if (ts.Minutes > 0)
    {
        outputDateTime = ts.Minutes == 1 ? ("1 minute ago") : (ts.Minutes.ToString() + " minutes ago");
    }
    else outputDateTime = "few seconds ago";

    return outputDateTime;
}
Kolappan N
  • 2,178
  • 2
  • 26
  • 31
Prashant Gupta
  • 581
  • 6
  • 10
5
var ts = new TimeSpan(DateTime.Now.Ticks - dt.Ticks);
Kolappan N
  • 2,178
  • 2
  • 26
  • 31
JoeyFur62
  • 257
  • 4
  • 6
5

I would provide some handy extensions methods for this and make the code more readable. First, couple of extension methods for Int32.

public static class TimeSpanExtensions {

    public static TimeSpan Days(this int value) {

        return new TimeSpan(value, 0, 0, 0);
    }

    public static TimeSpan Hours(this int value) {

        return new TimeSpan(0, value, 0, 0);
    }

    public static TimeSpan Minutes(this int value) {

        return new TimeSpan(0, 0, value, 0);
    }

    public static TimeSpan Seconds(this int value) {

        return new TimeSpan(0, 0, 0, value);
    }

    public static TimeSpan Milliseconds(this int value) {

        return new TimeSpan(0, 0, 0, 0, value);
    }

    public static DateTime Ago(this TimeSpan value) {

        return DateTime.Now - value;
    }
}

Then, one for DateTime.

public static class DateTimeExtensions {

    public static DateTime Ago(this DateTime dateTime, TimeSpan delta) {

        return dateTime - delta;
    }
}

Now, you can do something like below:

var date = DateTime.Now;
date.Ago(2.Days()); // 2 days ago
date.Ago(7.Hours()); // 7 hours ago
date.Ago(567.Milliseconds()); // 567 milliseconds ago
tugberk
  • 54,046
  • 58
  • 232
  • 321
5
/** 
 * {@code date1} has to be earlier than {@code date2}.
 */
public static String relativize(Date date1, Date date2) {
    assert date2.getTime() >= date1.getTime();

    long duration = date2.getTime() - date1.getTime();
    long converted;

    if ((converted = TimeUnit.MILLISECONDS.toDays(duration)) > 0) {
        return String.format("%d %s ago", converted, converted == 1 ? "day" : "days");
    } else if ((converted = TimeUnit.MILLISECONDS.toHours(duration)) > 0) {
        return String.format("%d %s ago", converted, converted == 1 ? "hour" : "hours");
    } else if ((converted = TimeUnit.MILLISECONDS.toMinutes(duration)) > 0) {
        return String.format("%d %s ago", converted, converted == 1 ? "minute" : "minutes");
    } else if ((converted = TimeUnit.MILLISECONDS.toSeconds(duration)) > 0) {
        return String.format("%d %s ago", converted, converted == 1 ? "second" : "seconds");
    } else {
        return "just now";
    }
}
Wai Ho Leung
  • 36
  • 1
  • 4
5

If you want to have an output like "2 days, 4 hours and 12 minutes ago", you need a timespan:

TimeSpan timeDiff = DateTime.Now-CreatedDate;

Then you can access the values you like:

timeDiff.Days
timeDiff.Hours

etc...

Nalaka526
  • 10,062
  • 20
  • 77
  • 115
Bgl86
  • 697
  • 6
  • 18
4
public string getRelativeDateTime(DateTime date)
{
    TimeSpan ts = DateTime.Now - date;
    if (ts.TotalMinutes < 1)//seconds ago
        return "just now";
    if (ts.TotalHours < 1)//min ago
        return (int)ts.TotalMinutes == 1 ? "1 Minute ago" : (int)ts.TotalMinutes + " Minutes ago";
    if (ts.TotalDays < 1)//hours ago
        return (int)ts.TotalHours == 1 ? "1 Hour ago" : (int)ts.TotalHours + " Hours ago";
    if (ts.TotalDays < 7)//days ago
        return (int)ts.TotalDays == 1 ? "1 Day ago" : (int)ts.TotalDays + " Days ago";
    if (ts.TotalDays < 30.4368)//weeks ago
        return (int)(ts.TotalDays / 7) == 1 ? "1 Week ago" : (int)(ts.TotalDays / 7) + " Weeks ago";
    if (ts.TotalDays < 365.242)//months ago
        return (int)(ts.TotalDays / 30.4368) == 1 ? "1 Month ago" : (int)(ts.TotalDays / 30.4368) + " Months ago";
    //years ago
    return (int)(ts.TotalDays / 365.242) == 1 ? "1 Year ago" : (int)(ts.TotalDays / 365.242) + " Years ago";
}

Conversion values for days in a month and year were taken from Google.

Jonathan Leffler
  • 666,971
  • 126
  • 813
  • 1,185
Nicolas Tyler
  • 9,372
  • 4
  • 38
  • 62
3

Surely an easy fix to get rid of the '1 hours ago' problem would be to increase the window that 'an hour ago' is valid for. Change

if (delta < 5400) // 90 * 60
{
    return "an hour ago";
}

into

if (delta < 7200) // 120 * 60
{
    return "an hour ago";
}

This means that something that occurred 110 minutes ago will read as 'an hour ago' - this may not be perfect, but I'd say it is better than the current situation of '1 hours ago'.

Dez
  • 5,010
  • 7
  • 37
  • 47
Cebjyre
  • 6,404
  • 3
  • 28
  • 57
3

Turkish localized version of Vincents answer.

    const int SECOND = 1;
    const int MINUTE = 60 * SECOND;
    const int HOUR = 60 * MINUTE;
    const int DAY = 24 * HOUR;
    const int MONTH = 30 * DAY;

    var ts = new TimeSpan(DateTime.UtcNow.Ticks - yourDate.Ticks);
    double delta = Math.Abs(ts.TotalSeconds);

    if (delta < 1 * MINUTE)
        return ts.Seconds + " saniye önce";

    if (delta < 45 * MINUTE)
        return ts.Minutes + " dakika önce";

    if (delta < 24 * HOUR)
        return ts.Hours + " saat önce";

    if (delta < 48 * HOUR)
        return "dün";

    if (delta < 30 * DAY)
        return ts.Days + " gün önce";

    if (delta < 12 * MONTH)
    {
        int months = Convert.ToInt32(Math.Floor((double)ts.Days / 30));
        return months + " ay önce";
    }
    else
    {
        int years = Convert.ToInt32(Math.Floor((double)ts.Days / 365));
        return years + " yıl önce";
    }
boyukbas
  • 758
  • 11
  • 18
2

This is my function, works like a charm :)

public static string RelativeDate(DateTime theDate)
        {
            var span = DateTime.Now - theDate;
            if (span.Days > 365)
            {
                var years = (span.Days / 365);
                if (span.Days % 365 != 0)
                    years += 1;
                return $"about {years} {(years == 1 ? "year" : "years")} ago";
            }
            if (span.Days > 30)
            {
                var months = (span.Days / 30);
                if (span.Days % 31 != 0)
                    months += 1;
                return $"about {months} {(months == 1 ? "month" : "months")} ago";
            }
            if (span.Days > 0)
                return $"about {span.Days} {(span.Days == 1 ? "day" : "days")} ago";
            if (span.Hours > 0)
                return $"about {span.Hours} {(span.Hours == 1 ? "hour" : "hours")} ago";
            if (span.Minutes > 0)
                return $"about {span.Minutes} {(span.Minutes == 1 ? "minute" : "minutes")} ago";
            if (span.Seconds > 5)
                return $"about {span.Seconds} seconds ago";

            return span.Seconds <= 5 ? "about 5 seconds ago" : string.Empty;
        }
VnDevil
  • 1,012
  • 12
  • 12
2

In a way you do your DateTime function over calculating relative time by either seconds to years, try something like this:

using System;

public class Program {
    public static string getRelativeTime(DateTime past) {
        DateTime now = DateTime.Today;
        string rt = "";
        int time;
        string statement = "";
        if (past.Second >= now.Second) {
            if (past.Second - now.Second == 1) {
                rt = "second ago";
            }
            rt = "seconds ago";
            time = past.Second - now.Second;
            statement = "" + time;
            return (statement + rt);
        }
        if (past.Minute >= now.Minute) {
            if (past.Second - now.Second == 1) {
                rt = "second ago";
            } else {
                rt = "minutes ago";
            }
            time = past.Minute - now.Minute;
            statement = "" + time;
            return (statement + rt);
        }
        // This process will go on until years
    }
    public static void Main() {
        DateTime before = new DateTime(1995, 8, 24);
        string date = getRelativeTime(before);
        Console.WriteLine("Windows 95 was {0}.", date);
    }
}

Not exactly working but if you modify and debug it a bit, it will likely do the job.

1
// Calculate total days in current year
int daysInYear;

for (var i = 1; i <= 12; i++)
    daysInYear += DateTime.DaysInMonth(DateTime.Now.Year, i);

// Past date
DateTime dateToCompare = DateTime.Now.Subtract(TimeSpan.FromMinutes(582));

// Calculate difference between current date and past date
double diff = (DateTime.Now - dateToCompare).TotalMilliseconds;

TimeSpan ts = TimeSpan.FromMilliseconds(diff);

var years = ts.TotalDays / daysInYear; // Years
var months = ts.TotalDays / (daysInYear / (double)12); // Months
var weeks = ts.TotalDays / 7; // Weeks
var days = ts.TotalDays; // Days
var hours = ts.TotalHours; // Hours
var minutes = ts.TotalMinutes; // Minutes
var seconds = ts.TotalSeconds; // Seconds

if (years >= 1)
    Console.WriteLine(Math.Round(years, 0) + " year(s) ago");
else if (months >= 1)
    Console.WriteLine(Math.Round(months, 0) + " month(s) ago");
else if (weeks >= 1)
    Console.WriteLine(Math.Round(weeks, 0) + " week(s) ago");
else if (days >= 1)
    Console.WriteLine(Math.Round(days, 0) + " days(s) ago");
else if (hours >= 1)
    Console.WriteLine(Math.Round(hours, 0) + " hour(s) ago");
else if (minutes >= 1)
    Console.WriteLine(Math.Round(minutes, 0) + " minute(s) ago");
else if (seconds >= 1)
    Console.WriteLine(Math.Round(seconds, 0) + " second(s) ago");

Console.ReadLine();
0

My way is much more simpler. You can tweak with the return strings as you want

    public static string TimeLeft(DateTime utcDate)
    {
        TimeSpan timeLeft = DateTime.UtcNow - utcDate;
        string timeLeftString = "";
        if (timeLeft.Days > 0)
        {
            timeLeftString += timeLeft.Days == 1 ? timeLeft.Days + " day" : timeLeft.Days + " days";
        }
        else if (timeLeft.Hours > 0)
        {
            timeLeftString += timeLeft.Hours == 1 ? timeLeft.Hours + " hour" : timeLeft.Hours + " hours";
        }
        else
        {
            timeLeftString += timeLeft.Minutes == 1 ? timeLeft.Minutes+" minute" : timeLeft.Minutes + " minutes";
        }
        return timeLeftString;
    }
Fred
  • 10,269
  • 4
  • 48
  • 63
Beingnin
  • 1,877
  • 13
  • 31
0

A "one-liner" using deconstruction and Linq to get "n [biggest unit of time] ago" :

TimeSpan timeSpan = DateTime.Now - new DateTime(1234, 5, 6, 7, 8, 9);

(string unit, int value) = new Dictionary<string, int>
{
    {"year(s)", (int)(timeSpan.TotalDays / 365.25)}, //https://en.wikipedia.org/wiki/Year#Intercalation
    {"month(s)", (int)(timeSpan.TotalDays / 29.53)}, //https://en.wikipedia.org/wiki/Month
    {"day(s)", (int)timeSpan.TotalDays},
    {"hour(s)", (int)timeSpan.TotalHours},
    {"minute(s)", (int)timeSpan.TotalMinutes},
    {"second(s)", (int)timeSpan.TotalSeconds},
    {"millisecond(s)", (int)timeSpan.TotalMilliseconds}
}.First(kvp => kvp.Value > 0);

Console.WriteLine($"{value} {unit} ago");

You get 786 year(s) ago

With the current year and month, like

TimeSpan timeSpan = DateTime.Now - new DateTime(2020, 12, 6, 7, 8, 9);

you get 4 day(s) ago

With the actual date, like

TimeSpan timeSpan = DateTime.Now - DateTime.Now.Date;

you get 9 hour(s) ago