Thursday, March 15, 2012

How to manipulate date in Android such as various formats and add or subtract certain number of days ?



//Add certain number of days to Today
       
int myDays = 3;

       
final Calendar c = Calendar.getInstance();
       
c.add(Calendar.DATE, myDays);  // number of days to add
       
int newDate =     (c.get(Calendar.YEAR) * 10000) + 
                           
((c.get(Calendar.MONTH) + 1) * 100) + 
                           
(c.get(Calendar.DAY_OF_MONTH));


//Subtract certain number of days to Today
       
int myDays = 3;

       
final Calendar c = Calendar.getInstance();
       
c.add(Calendar.DATE, (myDays * -1));  // number of days to subtract
       
int newDate =     (c.get(Calendar.YEAR) * 10000) + 
                           
((c.get(Calendar.MONTH) + 1) * 100) + 
                           
(c.get(Calendar.DAY_OF_MONTH));


//Change date format from yyyyMMdd to MM/dd/yy
       
SimpleDateFormat df = new SimpleDateFormat("yyyyMMdd");
           
Date date = null;
           
try {
               
date = df.parse(inputDate);
           
} catch (ParseException e) {
               
e.printStackTrace();
           
}
           
TextView dateText = (TextView) historyData.findViewById(R.id.mydate);
           
dateText.setText(DateFormat.format("MM/dd/yy",date));


//Change time format from military Hmmss to hh:mm:ss a

       
SimpleDateFormat df2 = new SimpleDateFormat("Hmmss");
           
Date date2 = null;
           
try {
               
date2 = df2.parse(inputTime);
           
} catch (ParseException e) {
               
e.printStackTrace();
           
}
           
TextView timeText = (TextView) historyData.findViewById(R.id.mytime);
           
timeText.setText(DateFormat.format("hh:mm:ss a",date2));

No comments:

Post a Comment