Android Programming : Adding minutes to time in hh:mm a format


Hi Guys, In some situation, we want to add some minutes to the predefined time range such as in my case, I want to add minutes {0,15,30,60,120,240} to my existing time range to perform some activity. Below is the code that implements the above behavior:

Below code is self explanatory:

//Global Variable

 private int[] iToincrement = {0,15,30,60,120,240};
 private static int _incCount = 0;
 private String strNewTime = null;

// call

for (_incCount = 0 ;  _incCount<iToincrement.length; _incCount++)
  {
      strNewTime = GetIncreasedTime("8:59 AM", iToincrement[_incCount]);
      // play with the new time in the variable strNewTime
  } 

//definition of GetIncreasedTime function

public String GetIncreasedTime(String strStartTime, int iMinute)
 {

  String[] hm = strStartTime.split(":");
  int hour = Integer.parseInt(hm[0]);
  String strMinWPMAM = hm[1];
  
  String[] minAMPM = strMinWPMAM.split(" ");
  int Min = Integer.parseInt(minAMPM[0]);
  String strPMAM = minAMPM[1];  

  int itotaltime = hour * 60 + Min;
  itotaltime += iMinute; 

  while (itotaltime < 0) 
  {   
    itotaltime += 1440;     
  }

  int nh = (itotaltime / 60) % 24;  
  int nm = itotaltime % 60;
  
  if (nh>=12)
  {
   strPMAM="PM";
  }else
  {
   strPMAM="AM";
  }  
    
  SimpleDateFormat sdf = new SimpleDateFormat("hh:mm", Locale.getDefault());
  Date DtNewTime;
  
  try {
   DtNewTime = sdf.parse(nh+":"+nm);
   Toast.makeText(MainActivity.this, "text : " + DtNewTime , Toast.LENGTH_LONG).show();
   return sdf.format(DtNewTime)+ " " + strPMAM;
  } catch (ParseException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }  
  return "1";  
 }
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