Calculate Relative Time in C#

Calculate relative time in C#

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";
}

Calculate relative time in C#

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";
}

How to parse relative time?

That's building a DSL (Domain specific language) for date handling. I don't know if somebody has done one for .NET but the construction of a DSL is fairly straightforward:

  1. Define the language precisely, which input forms you will accept and what will you do with ambiguities
  2. Construct the grammar for the language
  3. Build the finite state machine that parses your language into an actionable AST

You can do all that by yourself (with the help of the Dragon Book, for instance) or with the help of tools to the effect, as shown in this link.

Just by thinking hard about the possibilities you have a good chance, with the help of good UI examples, of covering more than half of the actual inputs your application will receive. If you aim to accept everything a human could possibly type, you can record the input determined as ambiguous and then add them to the grammar, whenever they can be interpreted, as there are things that will be inherently ambiguous.

Calculating relative dates using asp.net mvc

You don't need a library when a simple extension method can do it. This is an extension method that I have used:

public static string TimeAgo(this DateTime date)
{
TimeSpan timeSince = DateTime.Now.Subtract(date);
if (timeSince.TotalMilliseconds < 1) return "not yet";
if (timeSince.TotalMinutes < 1) return "just now";
if (timeSince.TotalMinutes < 2) return "1 minute ago";
if (timeSince.TotalMinutes < 60) return string.Format("{0} minutes ago", timeSince.Minutes);
if (timeSince.TotalMinutes < 120) return "1 hour ago";
if (timeSince.TotalHours < 24) return string.Format("{0} hours ago", timeSince.Hours);
if (timeSince.TotalDays < 2) return "yesterday";
if (timeSince.TotalDays < 7) return string.Format("{0} days ago", timeSince.Days);
if (timeSince.TotalDays < 14) return "last week";
if (timeSince.TotalDays < 21) return "2 weeks ago";
if (timeSince.TotalDays < 28) return "3 weeks ago";
if (timeSince.TotalDays < 60) return "last month";
if (timeSince.TotalDays < 365) return string.Format("{0} months ago", Math.Round(timeSince.TotalDays / 30));
if (timeSince.TotalDays < 730) return "last year"; //last but not least...
return string.Format("{0} years ago", Math.Round(timeSince.TotalDays / 365));
}

Source Link

Convert DateTime.Now to Time ago C#

You can either implement it yourself or use Humanizer library:

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"
DateTimeOffset.UtcNow.AddHours(1).Humanize() => "an hour from now"

Return if a date time is with 24 hours of another date time

Use Subtract method and TotalHours property.

System.DateTime date1 = new System.DateTime(2018, 4, 24, 22, 15, 0);
System.DateTime date2 = new System.DateTime(2018, 4, 24, 13, 2, 0);

System.TimeSpan diff1 = date2.Subtract(date1);

Console.WriteLine(diff1.TotalHours);

if(diff1.TotalHours >= -24 && diff1.TotalHours <=24)
{
Console.WriteLine("Within +/- 24 Hours");
}

How to calculate relative time spans using Java (code converting problem)?

You need to gain a deeper understanding of what this method actually does. Literally translating code from C# to Java won't give you a good solution and gets you stuck on language-specific details.

The two lines basically calculate the (absolute) difference in seconds of a timestamp to the current time. This can be written in Java as follows:

Duration duration = Duration.between(LocalDateTime.now(), timestamp);
long delta = duration.abs().getSeconds();

I'm just addressing your actual question here on how to transform these two lines. The provided snippet is not valid Java code and some parts are missing. delta is the difference in seconds which does not necessarily need to be a double. The argument you pass to your method should be named anything else than now because this is the timestamp you want to compare to the current time inside the method.

how do i calculate relative time in Listbox elements

You need something called a relative time converter.

If you search online, you'll find plenty of different implementations. A good one is definitely a part of Callisto toolkit.

You can also check out similar questions on StackOverflow such as this one.

Using a converter is really straightforward.

<TextBlock x:Name="TxtDuration" Text="{Binding Duration, Converter={StaticResource RelativeTimeConverter}}"/>

In this case the RelativeTimeConverter is declared as a static resource somewhere in your app.

Create an absolute or relative time period class in C#

You're basically trying to store the same data twice.

You can define any period of time by either:

  • A startdate and enddate, duration can be calculated by subtraction.
  • A startdate and duration (TimeSpan), Enddate can be calculated by adding the two.
  • You could do it with a duration and enddate but that's making things harder.

What you want to do is pick one way of storing it. If you want it the other way, write a function to calculate it. E.g:

public TimePeriod(DateTime startTime , DateTime endTime)
{
StartTime = startTime;
EndTime = endTime;
}

public TimePeriod(DateTime startTime , TimeSpan length)
{
StartTime = startTime;
EndTime = startTime + length;
}

public TimeSpan GetDuration()
{
return EndTime - StartTime;
}

//Else you can just get the StartTime or EndTime variable (DateTime)


Related Topics



Leave a reply



Submit