First Create a Class and Code like this :-
using System; using System.Web; public static class ActualTime { public static string TimeAgo(DateTime date) { DateTime currentDate = DateTime.Now;//To get current date TimeSpan actualTime = currentDate.Subtract(date); if (actualTime.TotalMilliseconds < 1) return "not yet"; if (actualTime.TotalMinutes < 1) return "just now"; if (actualTime.TotalMinutes < 2) return "1 minute ago"; if (actualTime.TotalMinutes < 60) return string.Format("{0} minutes ago", actualTime.Minutes); if (actualTime.TotalMinutes < 120) return "1 hour ago"; if (actualTime.TotalHours < 24) return string.Format("{0} hours ago", actualTime.Hours); if (actualTime.TotalDays == 1) return "yesterday"; if (actualTime.TotalDays < 7) return string.Format("{0} days ago", actualTime.Days); if (actualTime.TotalDays < 14) return "last week"; if (actualTime.TotalDays < 21) return "2 weeks ago"; if (actualTime.TotalDays < 28) return "3 weeks ago"; if (actualTime.TotalDays < 60) return "last month"; if (actualTime.TotalDays < 365) return string.Format("{0} months ago", Math.Round(actualTime.TotalDays / 30)); if (actualTime.TotalDays < 730) return "last year"; else { return string.Format("{0} years ago", Math.Round(actualTime.TotalDays / 365)); } } }
This class will return the output in string but we must pass parameter value in it to get the result
aspx page
Take One label and One textbox like this : <asp:TextBox ID="txtDate" runat="server" OnTextChanged="txtDate_TextChanged" AutoPostBack="true"></asp:TextBox> <asp:Label ID="lblDate" runat="server" Text="Actual time will show here"></asp:Label>
aspx.cs pageprotected void txtDate_TextChanged(object sender, EventArgs e) { DateTime userInputDate = Convert.ToDateTime(txtDate.Text); lblDate.Text = ActualTime.TimeAgo(userInputDate); }
Output
That’s it!!…..Happy Programming...
No comments:
Post a Comment