How can I calculate relative time using a C# language?
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";
}
Tags: c# time datetime datediff relative-time-span
Source: By Jeff Atwood as answer to the question
This code snippet was collected from stackoverflow, and is licensed under CC BY-SA 3.0
Related code-snippets:
- How do you convert decimal in C#?
- How do you calculate someone's age based on datetime?
- If a query result set is filled in LINQ with data then fill the data set or the table with data. This example is just that.
- How do I get a distinct, ordered list of names from a data table using LINQ?
- Decoding T-SQL CAST in C#/VB.NET.
- Do you like compression of files? How do you decompress them?
- How can I print an HTML document from a web service?
- What is the catch all algorithm?
- How do you sort a dictionary by value?
- WinForms ComboBox data binding gotcha WinForms combobox data binding gotcha WinForms ComboBox data binding gotcha WinForms ComboBox data binding gotcha WinForms ComboBox data binding gotcha WinForms ComboBox data binding gotcha WinForms ComboBox data binding gotcha gotcha
- What is the difference between Int and Integer in Java and C#?
- How to change version number on iOS?
- How can I create an object instance from a Type?
- How do I express the left join with aggregate SQL as LINQ query?
- What is the best way to use a database in c#?