I want to get the date , month and year from the particular date.
I have used below code :
String dob = "01/08/1990";
int month = 0, dd = 0, yer = 0;
try {
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");
Date d = sdf.parse(dob);
Calendar cal = Calendar.getInstance();
cal.setTime(d);
month = cal.get(Calendar.MONTH);
dd = cal.get(Calendar.DATE);
yer = cal.get(Calendar.YEAR);
} catch (Exception e) {
e.printStackTrace();
}
So from the above code i am getting month -0 , yer - 1990 and date - 8
But i want month - 01 , date - 08 and yer - 1990
.
I have defined the date format also but i am not getting perfect value from date, month and year.
Month in calendar will be from 0-11. You have to add +1 in month.
String dob = "01/08/1990";
String month = 0, dd = 0, yer = 0;
try {
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");
Date d = sdf.parse(dob);
Calendar cal = Calendar.getInstance();
cal.setTime(d);
month = checkDigit(cal.get(Calendar.MONTH)+1);
dd = checkDigit(cal.get(Calendar.DATE));
yer = checkDigit(cal.get(Calendar.YEAR));
} catch (Exception e) {
e.printStackTrace();
}
checkDigit method for adding preceeding zero. checkDigit() method returns String value. if You want to convert in integer then you can do like Integer.parseInt(YOUR_STRING);
// ADDS 0 e.g - 02 instead of 2
public String checkDigit (int number) {
return number <= 9 ? "0" + number : String.valueOf(number);
}