How can I display the difference of the date and time of a post and the current time ?
For example, If i posted an article on August 17, 2021 06:30AM, in the label it will display "Posted 2 years ago".
Or it will display like "2 years, 3 days ago". Or maybe add the time as well like "2 years, 3 days 1 hour 23 minutes 3 seconds ago"
I tried this but it displayed 239 days ago (and that depends on the Date I posted the article).
But what if the Date exceeds 1 year, or 4 years, will it display as "1 year ago" or "4 years ago" depending on the date?
private void PopulateArticle()
{
try
{
string articleId = this.Page.RouteData.Values["ArticleId"].ToString();
string articleTitle = this.Request.QueryString["Title"].ToString();
if (articleId != null)
{
string query = "SELECT [Title], [Body], [DatePosted] FROM [Articles] WHERE [ArticleId] = @ArticleId";
string connectionString = ConfigurationManager.ConnectionStrings["ConString"].ConnectionString;
using (SqlConnection con = new SqlConnection(connectionString))
{
using (SqlCommand cmd = new SqlCommand(query))
{
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmd.Parameters.AddWithValue("@ArticleId", articleId);
cmd.Connection = con;
sda.SelectCommand = cmd;
using (DataTable dt = new DataTable())
{
sda.Fill(dt);
lblBody.Text = dt.Rows[0]["Body"].ToString();
TitleLabel.Text = dt.Rows[0]["Title"].ToString();
DateTime PostedTime = Convert.ToDateTime(dt.Rows[0]["DatePosted"]);
Thread.Sleep(3 * 1000);
DateTime CurrentTime = DateTime.Now;
TimeSpan diff = CurrentTime - PostedTime;
timelbl.Text = $"Posted {(int)diff.TotalDays} days ago ";
}
}
}
}
}
}
catch (SqlException ex)
{
string msg = "Error:";
msg += ex.Message;
throw new Exception(msg);
}
}