Android Programming: Function for Time comparison


I have written below function to find if the current android system time is before/after/equal to the given time.

Below is the code from my MainActivity class which is self explanatory:

package com.aslsoft.pocapp;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
import java.util.TimeZone;

import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.widget.TextView;

public class MainActivity extends Activity {

 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);  
  
  TextView tv = (TextView) findViewById(R.id.tv);  
  tv.setText("Date Time : " + CompareTime("3:54 PM"));  
 }
 

 public String CompareTime(String strTimeToCompare)
 {
  Calendar cal = Calendar.getInstance(TimeZone.getDefault());
  int dtHour;
  int dtMin;
  int iAMPM;
  String strAMorPM=null;
  Date dtCurrentDate;
    
  SimpleDateFormat sdf = new SimpleDateFormat("hh:mm aa", Locale.getDefault());
  
  try {
   
   Date TimeToCompare = sdf.parse(strTimeToCompare);
   dtMin=cal.get(Calendar.MINUTE);
   dtHour=cal.get(Calendar.HOUR);   
   iAMPM=cal.get(Calendar.AM_PM);
   if (iAMPM == 1)
   {
    strAMorPM="PM";
   }
   
   if (iAMPM == 0)
   {
    strAMorPM="AM";
   }
   
   dtCurrentDate = sdf.parse(dtHour + ":" + dtMin + " " + strAMorPM);

   if(dtCurrentDate.after(TimeToCompare))
   {
    return "1";
   }
   if (dtCurrentDate.before(TimeToCompare))
   {
    return "2";
   }
   if (dtCurrentDate.equals(TimeToCompare))
   {
    return "3";
   }
  } catch (ParseException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
  return "4";
 } 

 @Override
 public boolean onCreateOptionsMenu(Menu menu) {
  // Inflate the menu; this adds items to the action bar if it is present.
  getMenuInflater().inflate(R.menu.activity_main, menu);
  return true;
 }
}

					
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s