Aspdotnet-Suresh

aspdotnet-suresh offers C#.net articles and tutorials,csharp dot net,asp.net articles and tutorials,VB.NET Articles,Gridview articles,code examples of asp.net 2.0 /3.5,AJAX,SQL Server Articles,examples of .net technologies

JQuery display time in facebook/ twitter formats like minute ago, hour ago, week ago in asp.net

Feb 16, 2012
Introduction:

In this article I will explain how to show time in facebook/ twitter formats like minute ago, hour ago, week ago in asp.net using JQuery.


Description:
  
In previous posts I explained many articles relating to
JQuery. Now I will explain another article relating to JQuery. If we share anything on facebook or twitter we will get time in different format like 1 minute ago, 1 hour ago, 1 week ago etc.
To implement this concept I am using previous post Repeater example in asp.net. After bind data to repeater control our date and time would be like this
We can change date and time format like facebook / twitter style (minute ago, hour ago, month ago etc) by using JQuery timeago plugin. This plugin automatically update our datetime without having any postback of page you can get this JQuery timeago plugin by downloading attached folder.
Before use this plugin I used other methods to change date and time format like facebook/twitter but I got one problem that is now I opened website during that time that is showing 1 minute ago. I stayed on that website upto 5 minutes but still that is showing 1 minute only if I refresh website then datetime value is updating but this JQuery timeago plugin automatically update our datetime without having any postsbacks.
To implement this one check previous post Repeater example in asp.net I am using same concept just adding new logic to change date and time format
After design data table and insert data in database by using above repeater post write the following code in your aspx page  to bind data o repeater control

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title>Sample to Display time in facebook/twitter format like 1 minute ago, 1 hour ago, 1 week ago, 1 month ago</title>
<script src="js/jquery.min.js" type="text/javascript"></script>
<script src="js/jquery.timeago.js" type="text/javascript"></script>
<script src="js/test_helpers.js" type="text/javascript"></script>
<script type="text/javascript">
jQuery(document).ready(function($) {
prepareDynamicDates();
$("label.timeago").timeago();
});

</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Repeater ID="RepDetails" runat="server">
<HeaderTemplate>
<table style=" border:1px solid #df5015; width:500px" cellpadding="0">
<tr style="background-color:#df5015; color:White">
<td colspan="2">
<b>Comments</b>
</td>
</tr>
</HeaderTemplate>
<ItemTemplate>
<tr style="background-color:#EBEFF0">
<td>
<table style="background-color:#EBEFF0;border-top:1px dotted #df5015; width:500px" >
<tr>
<td>
Subject:
<asp:Label ID="lblSubject" runat="server" Text='<%#Eval("Subject") %>' Font-Bold="true"/>
</td>
</tr>
</table>
</td>
</tr>
<tr>
<td>
<asp:Label ID="lblComment" runat="server" Text='<%#Eval("Comment") %>'/>
</td>
</tr>
<tr>
<td>
<table style="background-color:#EBEFF0;border-top:1px dotted #df5015;border-bottom:1px solid #df5015; width:500px" >
<tr>
<td>Post By: <asp:Label ID="lblUser" runat="server" Font-Bold="true" Text='<%#Eval("UserName") %>'/></td>
<td>Created Date: <label class="timeago" title="<%#Eval("PostedDate") %>" style=" font-weight:bold"></label></td>
</tr>
</table>
</td>
</tr>
<tr>
<td colspan="2">&nbsp;</td>
</tr>
</ItemTemplate>
<FooterTemplate>
</table>
</FooterTemplate>
</asp:Repeater>
</div>
</form>
</body>
</html>
If you observe above code in header section I added some of script files by using those files we can change date and time. To get those files download attached sample code and use it in your application.

Another thing here we need to know is label link

<label class="timeago" title="<%#Eval("PostedDate") %>" style=" font-weight:bold"/>
JQuery timeago plugin automatically change time format for label elements with class="timeago" and title.

After completion of aspx page design add following namespaces in code behind

C# Code

using System;
using System.Data;
using System.Data.SqlClient;
using System.IO;
After add namespace write the following code


private SqlConnection con = new SqlConnection("Data Source=SureshDasari;Initial Catalog=MySampleDB;Integrated Security=true");
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindRepeaterData();
}
}
//Bind Data to Repeater Control
protected void BindRepeaterData()
{
con.Open();
SqlCommand cmd = new SqlCommand("select * from Repeater_Table Order By PostedDate desc", con);
DataSet ds = new DataSet();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(ds);
if (ds.Tables[0].Rows.Count > 0)
{
RepDetails.Visible = true;
RepDetails.DataSource = ds;
RepDetails.DataBind();
}
else
{
RepDetails.Visible = false;
}

con.Close();
}
VB.NET Code

Imports System.Data
Imports System.Data.SqlClient
Imports System.IO

Partial Class _Default
Inherits System.Web.UI.Page
Private con As New SqlConnection("Data Source=SureshDasari;Initial Catalog=MySampleDB;Integrated Security=true")
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
If Not IsPostBack Then
BindDataList()
End If
End Sub
Protected Sub BindDataList()
con.Open()
'Query to get ImagesName and Description from database
Dim command As New SqlCommand("SELECT ImageName,Description from SlideShowTable", con)
Dim da As New SqlDataAdapter(command)
Dim dt As New DataTable()
da.Fill(dt)
dlImages.DataSource = dt
dlImages.DataBind()
con.Close()
End Sub

Protected Sub btnSubmit_Click(ByVal sender As Object, ByVal e As EventArgs)
'Get Filename from fileupload control
Dim filename As String = Path.GetFileName(fileuploadimages.PostedFile.FileName)
'Save images into SlideImages folder
fileuploadimages.SaveAs(Server.MapPath("SlideImages/" & filename))
'Open the database connection
con.Open()
'Query to insert images name and Description into database
Dim cmd As New SqlCommand("Insert into SlideShowTable(ImageName,Description) values(@ImageName,@Description)", con)
'Passing parameters to query
cmd.Parameters.AddWithValue("@ImageName", filename)
cmd.Parameters.AddWithValue("@Description", txtDesc.Text)
cmd.ExecuteNonQuery()
'Close dbconnection
con.Close()
txtDesc.Text = String.Empty
BindDataList()
End Sub
End Class
Now run your application check the output that would be like this   


After open your website stay on that website for 1 or 2 minutes and check your time in website that will be updated automatically.

Download sample code attached


 

If you enjoyed this post, please support the blog below. It's FREE!

Get the latest Asp.net, C#.net, VB.NET, jQuery, Plugins & Code Snippets for FREE by subscribing to our Facebook, Twitter, RSS feed, or by email.

subscribe by rss Subscribe by RSS subscribe by email Subscribe by Email

25 comments :

Anonymous said...

excellent

imran said...

fabulous

Anonymous said...

Suresh Sir
AAp ek code post kar sakte hai kya?
Google Map (API) Jis city ko dikna chaye use page load par dal kar dekha sakte hai in Asp.net code
Plz post this I need This Code ........................

sagar said...

thanks.....

kya aap facebook type comment box ka codding bata sakte he....agar he to kya name he vo bata ye ..
plz i need your help......

Anonymous said...

excellent code..

Pankaj Kumar said...

Sir,
Jquery of to show time in facebook/ twitter formats like minute ago, hour ago, week ago in asp.net using JQuery.
not working properly.....

Suresh Dasari said...

@Pankaj Kumar..
it's working perfectly. Please check your code

Santosh Pal said...

JQuery display time in facebook/ twitter formats like minute ago, hour ago, week ago in asp.net is not working properly.when i run this code its show Created Date: 4 months ago for all.

Suresh Dasari said...

@Santosh Pal...
Check your created dates range based on that only it will show..

Santosh Pal said...

Suresh Sir i have created 1 table and i have some data like
Id UserName Subject Comment PostedDate
11 sarfaraz Check ssjjfj 2012-06-01 16:26:00.000
12 santoshpal Pal good 2012-06-01 16:52:00.000
13 minal Check hi 2012-06-01 17:13:00.000

when i run my code its show Created Date: 4 months ago for all.
what i have to do extra things to get result
Plz help me sir.

Suresh Dasari said...

@Santhosh Pal...
Please change your date format to mm/date/year like 06/01/2012 then try it will work for you.

Santosh Pal said...

Thanks to his help Suresh sir

Vidit Tyagi said...

Its working perfectly but when we add new comment in a post all dates automatically hidden becoz at that moment ur jquery is not working properly becoz of data binding so i think

var ts = new TimeSpan(DateTime.UtcNow.Ticks - dt.Ticks);
double delta = Math.Abs(ts.TotalSeconds);

if (delta < 60)
{
return ts.Seconds == 1 ? "one second ago" : ts.Seconds + " seconds ago";
}
if (delta < 120)
{
return "a minute ago";
}
if (delta < 2700) // 45 * 60
{
return ts.Minutes + " minutes ago";
}
if (delta < 5400) // 90 * 60
{
return "an hour ago";
}
if (delta < 86400) // 24 * 60 * 60
{
return ts.Hours + " hours ago";
}
if (delta < 172800) // 48 * 60 * 60
{
return "yesterday";
}
if (delta < 2592000) // 30 * 24 * 60 * 60
{
return ts.Days + " days ago";
}
if (delta < 31104000) // 12 * 30 * 24 * 60 * 60
{
int months = Convert.ToInt32(Math.Floor((double)ts.Days / 30));
return months <= 1 ? "one month ago" : months + " months ago";
}
int years = Convert.ToInt32(Math.Floor((double)ts.Days / 365));
return years <= 1 ? "one year ago" : years + " years ago";

this is much better thn ur code

Suresh Dasari said...

@Moneysukh...
Whenver you enter comment and hidding date means that's the problem with your code. Please check it that's not the problem with this plugin.

Anonymous said...

Thanks in a million!!!!!! it really works i will observe this if the date of the client pc is not update to date

Anonymous said...

Hello Sir,
I have used this code and set date time format (MM/dd/YYYY) but it shows 14 hours ago ,17 hours ago like this for all records. please help thanks

Anonymous said...

how display twitter user comments in asp.net????

Anonymous said...

hi suresh garu

it is not working server side because label have no runat="server" wat we do.......

Anonymous said...

vcn bvn

Manjusha said...

Nice one..

NITIN GOSWAMI said...

Hello Suresh Dasari

I have added timeago plugin in my web application.It is similar post and comment system like facebook.After each post and comment i do a partial post back with ajax and bind the data back to repeater.But after the partial post back the time ago do not bind .If I remove update panel and use full post back it works fine.Pls help,seeking your help.

Thanks
Nitin Goswami

Anonymous said...

Hi Suresh,

Thanks for your code,i have one doubt that can we implement this same concept in the datalist. If yes,How to You..

Anonymous said...

Hi,
I got an answer for this.,thnks Suresh..how to use this same concept in data list..thnks for your code in advance.

Anonymous said...

hello Suresh
Its not working if we do partial post.I mean if we put some code with in updatepanel and doing operation then its not working.all the previous data is hidden.

Anonymous said...

I have created 3 linkbutton and each link button binded with listview,but on every click of linkbutton the time ago is not working.

Give your Valuable Comments

Note: Only a member of this blog may post a comment.

© 2015 Aspdotnet-Suresh.com. All Rights Reserved.
The content is copyrighted to Suresh Dasari and may not be reproduced on other websites without permission from the owner.