Application Using Difference Between Dates in Android Studio

Introduction

 
In this article, you will learn how to show when a post was posted, as you see on Facebook. In Facebook, you can see the time of the status, comments and so on as "Just Now", "1 day ago", "2 months ago and so on".
 
For doing this we will first store the post text and its time in a database. Later, while displaying, we will determine the difference between the present time and post time and display it accordingly.
 
Step 1
 
Create a new layout file.
 
Right-click on layout then select "New" -> "Layout resource file". Name it "first_layout" and add the following code to it:
  1. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    
  2.               android:orientation="vertical"    
  3.               android:layout_width="match_parent"    
  4.               android:layout_height="match_parent"    
  5.                android:background="#e6b4ac">    
  6.   <Button    
  7.       android:layout_width="wrap_content"    
  8.       android:layout_height="wrap_content"    
  9.       android:layout_marginTop="150dp"    
  10.       android:layout_marginLeft="120dp"    
  11.       android:text="View Post"    
  12.       android:id="@+id/view"    
  13.       android:background="@drawable/button_lay"    
  14.       android:paddingRight="10dp"    
  15.       android:paddingLeft="10dp"/>    
  16.   <Button    
  17.           android:layout_width="wrap_content"    
  18.           android:layout_height="wrap_content"    
  19.           android:layout_marginTop="150dp"    
  20.           android:layout_marginLeft="120dp"    
  21.           android:text="Write Post"    
  22.           android:id="@+id/write"    
  23.           android:background="@drawable/button_lay"    
  24.           android:paddingRight="10dp"    
  25.           android:paddingLeft="10dp"/>    
  26. </LinearLayout>   
The layout looks like:
 
im1.jpg
 
Step 2
 
Open "activity_main" and add the following code to it:
  1. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  2.     xmlns:tools="http://schemas.android.com/tools"  
  3.     android:layout_width="match_parent"  
  4.     android:layout_height="match_parent"  
  5.     android:paddingLeft="@dimen/activity_horizontal_margin"  
  6.     android:paddingRight="@dimen/activity_horizontal_margin"  
  7.     android:paddingTop="@dimen/activity_vertical_margin"  
  8.     android:paddingBottom="@dimen/activity_vertical_margin"  
  9.     tools:context=".MainActivity"  
  10.     android:background="#b7a3ca"  
  11.     android:orientation="vertical">  
  12.   <TextView  
  13.       android:layout_width="wrap_content"  
  14.       android:layout_height="wrap_content"  
  15.       android:text="@string/wats"  
  16.       android:textSize="30dp"  
  17.        />  
  18.   <EditText  
  19.       android:layout_height="wrap_content"  
  20.       android:layout_width="fill_parent"  
  21.       android:layout_marginLeft="10dp"  
  22.       android:layout_marginTop="50dp"  
  23.       android:layout_marginRight="10dp"  
  24.       android:scrollbars="vertical"  
  25.       android:id="@+id/postTxt"  
  26.         />  
  27.   <Button  
  28.       android:layout_width="wrap_content"  
  29.       android:layout_height="wrap_content"  
  30.       android:layout_marginTop="200dp"  
  31.       android:layout_marginLeft="120dp"  
  32.       android:text="POST"  
  33.       android:background="@drawable/button_lay"  
  34.       android:id="@+id/submit"  
  35.             />  
  36. </LinearLayout> 
The layout looks like:
 
im2.jpg
 
Step 3
 
Create a new layout file for viewing the thoughts/posts.
 
Right-click on layout then select "New" -> "Layout resource file". Name it as "view_layout2" and add the following code to it:
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <TextView xmlns:android="http://schemas.android.com/apk/res/android"  
  3.           android:layout_width="fill_parent"  
  4.           android:layout_height="wrap_content"  
  5.           android:padding="10dp"  
  6.           android:textSize="20sp"  
  7.           android:background="#459890"  
  8.           >  
  9. </TextView> 
The layout looks like:
 
im3.jpg
 
Step 4
 
Open "MainActivity" and add the following code to it:
  1. package com.chhavi.posttimimgs;  
  2.    
  3. import android.content.Context;  
  4. import android.content.Intent;  
  5. import android.os.Bundle;  
  6. import android.app.Activity;  
  7. import android.util.Log;  
  8. import android.view.Menu;  
  9. import android.view.View;  
  10. import android.widget.Button;  
  11. import java.sql.Date;  
  12. import java.text.SimpleDateFormat;  
  13. import java.util.Calendar;  
  14.    
  15. public class MainActivity extends Activity {  
  16.     Button view;  
  17.     Button write;  
  18.     final Context context=this;  
  19.    
  20.     @Override  
  21.     protected void onCreate(Bundle savedInstanceState) {  
  22.         super.onCreate(savedInstanceState);  
  23.         setContentView(R.layout.first_layout);  
  24.    
  25.         view=(Button)findViewById(R.id.view);  
  26.         write=(Button)findViewById(R.id.write);  
  27.    
  28.         view.setOnClickListener(new View.OnClickListener() {  
  29.             @Override  
  30.             public void onClick(View v) {  
  31.                 Intent i=new Intent(context,ViewPost.class);  
  32.                 startActivity(i);  
  33.             }  
  34.         });  
  35.    
  36.         write.setOnClickListener(new View.OnClickListener() {  
  37.             @Override  
  38.             public void onClick(View v) {  
  39.                 Intent i=new Intent(context,WritePost.class);  
  40.                 startActivity(i);  
  41.             }  
  42.         });  
  43.     }  
  44.    
  45.     @Override  
  46.     public boolean onCreateOptionsMenu(Menu menu) {  
  47.         // Inflate the menu; this adds items to the action bar if it is present.  
  48.         getMenuInflater().inflate(R.menu.main, menu);  
  49.         return true;  
  50.     }  

Step 5
 
Create a new Java file.
 
Right-click on the same package then select "New" -> "Java class". Name this "WritePost" and add the following code to it:
  1. package com.chhavi.posttimimgs;  
  2.    
  3. import android.app.Activity;  
  4. import android.content.ContentValues;  
  5. import android.database.sqlite.SQLiteDatabase;  
  6. import android.os.Bundle;  
  7. import android.util.Log;  
  8. import android.view.View;  
  9. import android.widget.Button;  
  10. import android.widget.EditText;  
  11. import android.widget.Toast;  
  12. import java.util.Calendar;  
  13.    
  14. public class WritePost extends Activity {  
  15.    
  16.     Button submit;  
  17.     EditText txt;  
  18.     static int count=1;  
  19.     private ThoughtsDataSource dataSource;  
  20.    
  21.     @Override  
  22.     protected void onCreate(Bundle savedInstanceState) {  
  23.         super.onCreate(savedInstanceState);  
  24.         setContentView(R.layout.activity_main);  
  25.    
  26.         txt=(EditText)findViewById(R.id.postTxt);  
  27.         submit=(Button)findViewById(R.id.submit);  
  28.         dataSource = new ThoughtsDataSource(WritePost.this);  
  29.         submit.setOnClickListener(new View.OnClickListener() {  
  30.             @Override  
  31.             public void onClick(View v) {  
  32.                try{  
  33.                    dataSource.open();  
  34.                    Calendar cal=Calendar.getInstance();  
  35.                    ThoughtData data = new ThoughtData();  
  36.                    data.setThought(txt.getText().toString());  
  37.                    data.setDateTimeString(cal.getTime().toString());  
  38.                     int date= Calendar.DAY_OF_MONTH;  
  39.                     int hr=Calendar.HOUR_OF_DAY;  
  40.                     int amPm=Calendar.AM_PM;  
  41.                     int day=Calendar.DAY_OF_WEEK;  
  42.    
  43.                    if(dataSource.createThought(data)>0)  
  44.                    {  
  45.                        Toast.makeText(WritePost.this"Thought posted successfully"1000).show();  
  46.                        finish();  
  47.                    }  
  48.                }  
  49.                catch(Exception e)  
  50.                {  
  51.                    Log.i("exception in creating.........",e+"");  
  52.                }  
  53.             }  
  54.         });  
  55.     }  

Step 6
 
Right-click on the same package then select "New" -> "Java class". Name this "SQLiteHelper" and add the following code to it:
  1. package com.chhavi.posttimimgs;  
  2.    
  3. import android.content.Context;  
  4. import android.database.sqlite.SQLiteDatabase;  
  5. import android.database.sqlite.SQLiteDatabase.CursorFactory;  
  6. import android.database.sqlite.SQLiteOpenHelper;  
  7.    
  8. public class SQLiteHelper extends SQLiteOpenHelper {  
  9.    
  10.     public static final String TABLE_TIMING = "timing";  
  11.     public static final String COLUMN_ID = "_id";  
  12.     public static final String COLUMN_THOUGHT = "thought";  
  13.     public static final String COLUMN_DATETIME = "dateTime";  
  14.     private static final String DATABASE_NAME = "timingDB.db";  
  15.     private static final int DATABASE_VERSION = 1;   
  16.     private static final String DATABASE_CREATE = "create table "  
  17.             + TABLE_TIMING + "(" + COLUMN_ID  
  18.             + " integer primary key AUTOINCREMENT NOT NULL , " + COLUMN_THOUGHT  
  19.             + " text not null, " + COLUMN_DATETIME  
  20.             + " text not null);";  
  21.    
  22.     public SQLiteHelper(Context context, String name, CursorFactory factory, int version) {  
  23.         super(context, name, factory, version);  
  24.         // TODO Auto-generated constructor stub  
  25.     }  
  26.    
  27.     public SQLiteHelper(Context context) {  
  28.         super(context, DATABASE_NAME, null, DATABASE_VERSION);  
  29.     }  
  30.    
  31.     @Override  
  32.     public void onCreate(SQLiteDatabase db) {  
  33.         // TODO Auto-generated method stub  
  34.         db.execSQL(DATABASE_CREATE);  
  35.     }  
  36.    
  37.     @Override  
  38.     public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {  
  39.         // TODO Auto-generated method stub  
  40.         db.execSQL("DROP TABLE IF EXISTS " + TABLE_TIMING);  
  41.         onCreate(db);  
  42.     }  

Step 7
 
Right-click on the same package then select "New" -> "Java class". Name this "ThoughtData" and add the following code to it:
  1. package com.chhavi.posttimimgs;  
  2.    
  3. public class ThoughtData {  
  4.     String thought;  
  5.     String dateTimeString;  
  6.    
  7.     public String getThought() {  
  8.         return thought;  
  9.     }  
  10.     public void setThought(String thought) {  
  11.         this.thought = thought;  
  12.     }  
  13.     public String getDateTimeString() {  
  14.         return dateTimeString;  
  15.     }  
  16.     public void setDateTimeString(String dateTimeString) {  
  17.         this.dateTimeString = dateTimeString;  
  18.     }  

Step 8
 
Right-click on the same package then select "New" -> "Java class". Name this "ThoughtDataSource" and add the following code to it:
  1. package com.chhavi.posttimimgs;  
  2.    
  3. import java.io.IOException;  
  4. import java.util.ArrayList;  
  5. import android.content.ContentValues;  
  6. import android.content.Context;  
  7. import android.database.Cursor;  
  8. import android.database.SQLException;  
  9. import android.database.sqlite.SQLiteDatabase;  
  10.    
  11. public class ThoughtsDataSource {  
  12.    
  13.     private SQLiteDatabase database;  
  14.     private SQLiteHelper dbHelper;  
  15.     private String[] allColumns = { SQLiteHelper.COLUMN_ID,  
  16.             SQLiteHelper.COLUMN_THOUGHT, SQLiteHelper.COLUMN_DATETIME };  
  17.    
  18.     public ThoughtsDataSource(Context context) {  
  19.       dbHelper = new SQLiteHelper(context);  
  20.     }  
  21.    
  22.     public void open() throws SQLException {  
  23.       database = dbHelper.getWritableDatabase();  
  24.     }  
  25.    
  26.     public void close() {  
  27.       dbHelper.close();  
  28.     }  
  29.    
  30.     public long createThought(ThoughtData data) {  
  31.         ContentValues values = new ContentValues();  
  32.         values.put(SQLiteHelper.COLUMN_THOUGHT, data.getThought());  
  33.         values.put(SQLiteHelper.COLUMN_DATETIME, data.getDateTimeString());  
  34.         long insertId = database.insert(SQLiteHelper.TABLE_TIMING, null,  
  35.             values);  
  36.         return insertId;  
  37.     }  
  38.    
  39.     public void deleteThought(long id) {  
  40.       database.delete(SQLiteHelper.TABLE_TIMING, SQLiteHelper.COLUMN_ID  
  41.           + " = " + id, null);  
  42.     }  
  43.    
  44.     public void deleteAllThoughts() {  
  45.         database.delete(SQLiteHelper.TABLE_TIMING, ""null);  
  46.     }  
  47.    
  48.     public ArrayList<ThoughtData> getAllResources() {  
  49.         ArrayList<ThoughtData> resources = new ArrayList<ThoughtData>();  
  50.         Cursor cursor = database.query(SQLiteHelper.TABLE_TIMING,allColumns, nullnullnullnullnull);  
  51.    
  52.         cursor.moveToFirst();  
  53.         while (!cursor.isAfterLast()) {  
  54.             try {  
  55.                 ThoughtData data;  
  56.                 data = cursorToResourceData(cursor);  
  57.                 resources.add(data);  
  58.             } catch (Exception e) {  
  59.                 // TODO Auto-generated catch block  
  60.                 e.printStackTrace();  
  61.             }  
  62.    
  63.             cursor.moveToNext();  
  64.         }  
  65.    
  66.         cursor.close();  
  67.         return resources;  
  68.       }  
  69.    
  70.     private ThoughtData cursorToResourceData(Cursor cursor) throws Exception {  
  71.         ThoughtData resourceData = new ThoughtData();  
  72.         resourceData.setThought(cursor.getString(1));  
  73.         resourceData.setDateTimeString(cursor.getString(2));  
  74.    
  75.         return resourceData;  
  76.       }  

Step 9
 
Right-click on the same package then select "New" -> "Java class". Name this "ViewPost" and add the following code to it:
  1. package com.chhavi.posttimimgs;  
  2.    
  3. import android.app.Activity;  
  4. import android.app.ListActivity;  
  5. import android.content.Context;  
  6. import android.database.Cursor;  
  7. import android.database.sqlite.SQLiteDatabase;  
  8. import android.os.Bundle;  
  9. import android.util.Log;  
  10. import android.view.View;  
  11. import android.widget.AdapterView;  
  12. import android.widget.ArrayAdapter;  
  13. import android.widget.ListAdapter;  
  14. import android.widget.ListView;  
  15. import android.widget.SimpleAdapter;  
  16. import java.text.DateFormat;  
  17. import java.text.SimpleDateFormat;  
  18. import java.util.ArrayList;  
  19. import java.util.Calendar;  
  20. import java.util.Date;  
  21. import java.util.GregorianCalendar;  
  22. import java.util.HashMap;  
  23. import java.util.Locale;  
  24. import java.util.concurrent.TimeUnit;  
  25.    
  26. public class ViewPost extends ListActivity  
  27. {  
  28.     final Context context=this;  
  29.     ListView lv ;  
  30.     ArrayList<String> allPost= new ArrayList<String>();  
  31.     private ThoughtsDataSource dataSource;  
  32.    
  33.     @Override  
  34.     protected void onCreate(Bundle savedInstanceState) {  
  35.         super.onCreate(savedInstanceState);  
  36.    
  37.         Calendar cal=Calendar.getInstance();  
  38.         Date now=cal.getTime();  
  39.         dataSource = new ThoughtsDataSource(ViewPost.this);  
  40.         try{  
  41.    
  42.             dataSource.open();  
  43.             ArrayList<ThoughtData> allData = new ArrayList<ThoughtData>();  
  44.             allData  = dataSource.getAllResources();  
  45.             ThoughtData data;  
  46.             for (int i = 0; i < allData.size(); i++) {  
  47.                 data = allData.get(i);  
  48.    
  49.                 Log.i("Value of i......",i+"");  
  50.    
  51.                 String time=data.getDateTimeString();  
  52.                 Log.i("time.............",time);  
  53.    
  54.                 DateFormat df=new SimpleDateFormat("E MMM d HH:mm:ss Z yyyy");// M d HH:mm:ssZ yyyy  
  55.                 Date postTime=df.parse(time);  
  56.                 Log.i("Only date.........****...", postTime + "");  
  57.    
  58.                 //system time  
  59.                 Log.i("System time........",now.toString());  
  60.    
  61.                 long diff=(now.getTime()-postTime.getTime())/1000;  
  62.                 Log.i("difference in sec...........", diff+"");  
  63.                 Log.i("time only for now.........",now.getTime()+"");  
  64.                 Log.i("time only for postTime.........",postTime.getTime()+"");  
  65.    
  66.                 //for months  
  67.                 Calendar calObj = Calendar.getInstance();  
  68.                 calObj.setTime(postTime);  
  69.                 int m=calObj.get(Calendar.MONTH);  
  70.                 Log.i("post time month............", m+"");  
  71.    
  72.                 Calendar calObjNow = Calendar.getInstance();  
  73.                 calObj.setTime(now);  
  74.                 int mNow=calObj.get(Calendar.MONTH);  
  75.                 Log.i("now month............", mNow+"");  
  76.    
  77.    
  78.                 String disTime="";  
  79.                 if(diff<15)  
  80.                 {  
  81.                     disTime="\nJust Now";  
  82.                 }  
  83.                 else if(diff<60)  
  84.                 {  
  85.                     disTime="\n"+diff+" seconds ago";  
  86.                 }  
  87.                 else if(diff<3600// until 1 hr  
  88.                 {  
  89.                     long temp=diff/60;  
  90.                     if(temp==1)  
  91.                        disTime="\n"+temp+" min ago";  
  92.                     else  
  93.                         disTime="\n"+temp+" mins ago";  
  94.                 }  
  95.                 else if(diff<(24*3600)) // until 24 hrs  
  96.                 {  
  97.                     long temp=diff/3600;  
  98.                     if(temp==1)  
  99.                         disTime="\n"+temp+" hr ago";  
  100.                     else  
  101.                         disTime="\n"+temp+" hrs ago";  
  102.                 }  
  103.                 else if(diff<(24*3600*7)) //until 7 days  
  104.                 {  
  105.                     long temp=diff/(3600*24);  
  106.                     if (temp==1)  
  107.                          disTime="\nyesterday";  
  108.                     else  
  109.                         disTime="\n"+temp+" days ago";  
  110.                 }  
  111.                 else if(diff<((24*3600*365))) // no. of  months.. until 1 yr  
  112.                 {  
  113.                     //long temp=diff/(3600*24;  
  114.    
  115.                     if(diff<=1)  
  116.                     {  
  117.                      if(diff<1)  
  118.                      {  
  119.                          long weeks=diff/7;  
  120.                          if(weeks<1)  
  121.                                 disTime="last week";  
  122.                          else  
  123.                                 disTime=weeks+" weeks ago";  
  124.                      }  
  125.                         else  
  126.                              disTime="1 month ago";  
  127.                     }  
  128.    
  129.                     else  
  130.                     {  
  131.                         int diffMonth=mNow-m;  
  132.                         disTime="\n"+diffMonth+" months ago";  
  133.                     }   
  134.    
  135.                 }  
  136.                 else  
  137.                 {  
  138.                     disTime="\n"+data.dateTimeString;  
  139.                 }  
  140.    
  141.                 allPost.add(data.thought + "\n" + disTime);  
  142.             }  
  143.    
  144.             setListAdapter(new ArrayAdapter<String>(this, R.layout.view_layout2,allPost));  
  145.    
  146.             ListView listView = getListView();  
  147.             listView.setTextFilterEnabled(true);  
  148.    
  149.             listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {  
  150.                 @Override  
  151.                 public void onItemClick(AdapterView<?> parent, View view, int position, long id) {  
  152.    
  153.                 }  
  154.             });  
  155.    
  156.         }  
  157.         catch(Exception e)  
  158.         {  
  159.             e.printStackTrace();  
  160. //            Log.i("Exception in db....", e + "");  
  161.         }  
  162.     }  

In the code above, "diff" is the difference between the two dates (the date on which the thought was posted and current date) in seconds. "disTime" gives the time that will be displayed, for example: "Just Now" will be displayed for thought posted "15 sec ago", time in seconds will be displayed for thought posted less than a minute ago and so on.
 
Step 10
 
Do the following changes in "AndroidManifest.xml":
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <manifest xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     package="com.chhavi.posttimimgs"  
  4.     android:versionCode="1"  
  5.     android:versionName="1.0" >  
  6.    
  7.   <uses-sdk  
  8.       android:minSdkVersion="8"  
  9.       android:targetSdkVersion="17" />  
  10.    
  11.   <application  
  12.       android:allowBackup="true"  
  13.       android:icon="@drawable/ic_launcher"  
  14.       android:label="@string/app_name"  
  15.       android:theme="@style/AppTheme" >  
  16.     <activity  
  17.         android:name="com.chhavi.posttimimgs.MainActivity"  
  18.         android:label="@string/app_name" >  
  19.       <intent-filter>  
  20.         <action android:name="android.intent.action.MAIN" />  
  21.    
  22.         <category android:name="android.intent.category.LAUNCHER" />  
  23.       </intent-filter>  
  24.     </activity>  
  25.     <activity  
  26.        android:name="com.chhavi.posttimimgs.ViewPost"  
  27.        android:label="@string/app_name" >  
  28.     </activity>  
  29.     <activity  
  30.        android:name="com.chhavi.posttimimgs.WritePost"  
  31.        android:label="@string/app_name" >  
  32.     </activity>  
  33.   </application>  
  34. </manifest> 
Output snapshots:
 
im4.jpg
 
Selecting "Write Post" will give you:
 
im5.jpg
 
Selecting "View Post" will give you:
 
im6f.jpg


Similar Articles