18 June 2017 Sudhanshu Ranjan 281

Time ago function for C#, asp.net, MVC

Guys, This C# code might be very useful for you. This function will return time in string format. Most of the Forums and social networking website use this function.

I have implemented through the extension method but you can use in same way or can change.

       public static string Time_Ago_Function(this DateTime dateTime)
        {
            string str_post_time = string.Empty;
            var timeSpan = DateTime.Now.Subtract(dateTime);

            if (timeSpan <= TimeSpan.FromSeconds(60))
            {
                str_post_time = string.Format("{0} seconds ago", timeSpan.Seconds);
            }
            else if (timeSpan <= TimeSpan.FromMinutes(60))
            {
                str_post_time = timeSpan.Minutes > 1 ? String.Format("about {0} minutes ago", timeSpan.Minutes) : "about a minute ago";
            }
            else if (timeSpan <= TimeSpan.FromHours(24))
            {
                str_post_time = timeSpan.Hours > 1 ? String.Format("about {0} hours ago", timeSpan.Hours) : "about an hour ago";
            }
            else if (timeSpan <= TimeSpan.FromDays(30))
            {
                str_post_time = timeSpan.Days > 1 ? String.Format("about {0} days ago", timeSpan.Days) : "yesterday";
            }
            else if (timeSpan <= TimeSpan.FromDays(365))
            {
                str_post_time = timeSpan.Days > 30 ? String.Format("about {0} months ago", timeSpan.Days / 30) : "about a month ago";
            }
            else
            {
                str_post_time = timeSpan.Days > 365 ? String.Format("about {0} years ago", timeSpan.Days / 365) : "about a year ago";
            }

            return str_post_time;
        }

 

Example -

Time Ago Function

 

If any query feel free to comment or ask.

Please share with your friends...!

Thank You.!! 

You can share at :

About Author
Sudhanshu Kumar Ranjan | Lead Engineer at HCL Technologies | Expertise in Microsoft Technology | Author | Blogger | Programmer
Know More
Connect with him on Facebook | Google+ | LinkedIn | Twitter

Recommended Post

Leave a comment

About Dotnet Cube

It's my blog - Dotnet Cube, where you will learn and get solutions about programming, web designing and development. I started this website to share my knowledge and experience which might help someone.

You can get more details about me and my blog at About Us page.

Subscribe Newsletter

Subscribe to our monthly newsletter to get the latest industry news, Media Group updates and our current specials.

Follow On Us...

Home | About | Advertise | Copyrights | Privacy | Contact | Admin

Copyrights © 2015-2017 dotnetcube.com. All rights reserved