Reputation: 219
Hi everyone in my program i receive a date like: 2015-01-18
It's a calendar object and i need to get the day, month and the year from the object. Right now i do something like:
int day = date.get(Calendar.DAY_OF_MONTH);
int month = date.get(Calender.MONTH + 1);
int year = date.get(Calender.Year);
The output is:
day = 18
month = 1
year = 2015
My problem is that i wanna get the month in this case like 01 and not 1 because that value is parsed later on my code and needs to be on that format. Is ugly to append the 0 before that 1 so anyone knoenter code herews a better way to do this? Thanks
Upvotes: 1
Views: 21106
Reputation: 10433
You need to
int month = cal.get(Calender.MONTH) + 1; // 0..11 -> 1..12
to get the int for the month (the + must be outside the argument).
If you need a string with a leading zero from that integer, you can use textformat:
System.out.printf("month=%02d%n", month);
String monthStr = String.format("%02d", month);
But, you actually do not have to take the route via ints, you can directly format parts of a Date
into strings:
monthStr = new SimpleDateFormat("MM", Locale.ENGLISH).format(cal.getTime());
Upvotes: 4
Reputation: 19231
If you need to pass the data as "01" an int
is the wrong datatype. You need to pass it as a String
. You can format the date using SimpleDateFormat
. That way you can choose which elements to pick from the date and the format they should have. Example:
final Calendar calendar = Calendar.getInstance();
final Date date = calendar.getTime();
String day = new SimpleDateFormat("dd").format(date); // always 2 digits
String month = new SimpleDateFormat("MM").format(date); // always 2 digits
String year = new SimpleDateFormat("yyyy").format(date); // 4 digit year
You can also format the full date like this:
String full = new SimpleDateFormat("yyyy-MM-dd").format(date); // e.g. 2015-01-18
The JavaDoc for SimpleDateFormat fully explains the various formatting options. Please note that SimpleDateFormat
is not thread safe.
Upvotes: 6