Monday, May 14, 2012

Set “date” with two ways: in Android ?


First Way:
If you are retrieving date directly from db then take it in String
Then check whether there that date is null or not.
Like shown below:
String strRequiredDate = ClassObject.getMyDate();
if(strExpirationDate != null)
{
String strDate;
SimpleDateFormat objDateFormat;
Date objDate;
objDateFormat = new SimpleDateFormat(“dd MMM yyyy HH:mm”);
objDateFormat.setTimeZone(Calendar.getInstance().getTimeZone());
objDate = objDateFormat.parse(strRequiredDate);
strDate = DateFormat.getDateFormat(getApplicationContext()).format(objDate);
objDateFormat = new SimpleDateFormat(“hh:mm aaa”);
objDateFormat.setTimeZone(Calendar.getInstance().getTimeZone());
strDate = strDate + “  ” + objDateFormat.format(objDate);
btnPickDateTime.setText(strDate);
btnPickDateTime.setVisibility(View.VISIBLE);
}
Output:
04/01/2013 09:35 AM

Second Way:
SimpleDateFormat formatter;
Date objDate = new Date();
//Date values
int year;
int dayOfMonth;
int monthOfYear;
//Time values
int hour;
int min;
year = objDatePicker.getYear() – 1900;
dayOfMonth = objDatePicker.getDayOfMonth();
monthOfYear = objDatePicker.getMonth();
hour = objTimePicker.getCurrentHour();
min = objTimePicker.getCurrentMinute();
objDate.setDate(dayOfMonth);
objDate.setMonth(monthOfYear);
objDate.setYear(year);
objDate.setHours(hour);
objDate.setMinutes(min);
_objExpiryDate = objDate;
formatter=new SimpleDateFormat(DATE_FORMAT);
btnPickDateTime.setText(formatter.format(objDate));
Where as objDatePicker is nothing but my DatePicker control to select the perticular date.
objTimePicker is nothing but my TimePicker control to select the perticular time.
Output:
4 Jan 2013 09:35

No comments:

Post a Comment