Management of date time system in web application is an important task of a website programmer. Facebook and Twitter like website uses special conversion algorithms for time representation and synchronization. On the other hand Programming language like C#, stores date time in there special formats for system uses. We can use .ToString(<FORMAT>) method for special time-date formatting. You can read more about this on Microsoft Website.
I have create a mehtod/function to obtain behavior of this date-time in c# programming language.
Function Accepts the Date-Time type Parameters and returns the string format of date time for user friendly representations.
Here is implementation in C# Language:
public string TimeFromDateTime(DateTime dt)
{
TimeSpan span = DateTime.Now - dt;
if (dt < DateTime.Now)
{
if (span.Days > 365)
{
return dt.ToString("dd MMMM yyyy");
}
if (span.Days > 30)
{
return dt.ToString("ddd, dd MMMM yyyy");
}
if (span.Days > 0)
{
return dt.ToString("ddd, d MMM h:mm tt");
}
if (span.Hours > 0)
{
return String.Format("{0} {1} ago", span.Hours, span.Hours == 1 ? "hr" : "hrs");
}
if (span.Minutes > 0)
{
return String.Format("{0} {1} ago", span.Minutes, span.Minutes == 1 ? "min" : "mins");
}
if (span.Seconds > 5)
{
return String.Format("{0} sec ago", span.Seconds);
}
if (span.Seconds <= 5)
{
return "just now";
}
}
else
{
span = dt - DateTime.Now;
if (span.Days > 365)
{
return "Upcoming " + dt.ToString("dd MMMM yyyy");
}
if (span.Days > 30)
{
return "Upcoming "+dt.ToString("dd MMMM yyyy");
}
if (span.Days > 0)
return String.Format("about {0} {1} from now", span.Days, span.Days == 1 ? "day" : "days");
if (span.Hours > 0)
return String.Format("about {0} {1} from now", span.Hours, span.Hours == 1 ? "hour" : "hours");
if (span.Minutes > 0)
return String.Format("about {0} {1} from now", span.Minutes,
span.Minutes == 1 ? "minute" : "minutes");
if (span.Seconds > 5)
return String.Format("about {0} seconds from now", span.Seconds);
if (span.Seconds == 0)
return "just now";
}
return "Unknown Time is Left";
}
Thankyou For reading this post. Report any problem or error in comments section.
#WithLoveFromJaskaranSHSD
Comments
Post a Comment