سؤال

I've a problem to convert a date in other format in java (I'm using JodaTime). In fact, I've a formatted local date as is:

24/apr/14 (Italian format date...but other local formats are possible)

I would like separate the day, month and year and to see in output:

gg: 24
MM: 04
yyyy: 2014

How can I retrieve this data?

Thanks!!

هل كانت مفيدة؟

المحلول

Correcting your assumption "24/apr/14" as italian (both JodaTime and JDK say: d-MMM-yyyy) I have found this way:

String input = "24-apr-2014";
Locale locale = Locale.ITALY;

DateTimeFormatter dtf = DateTimeFormat.mediumDate().withLocale(locale);
LocalDate date = dtf.parseLocalDate(input);

int dayOfMonth = date.getDayOfMonth();
int month = date.getMonthOfYear();
int year = date.getYear();

DecimalFormat df = new DecimalFormat("00");
String dayOfMonthAsText = df.format(dayOfMonth);
String monthAsText = df.format(month);
String yearAsText = new DecimalFormat("0000").format(year);

System.out.println(dayOfMonthAsText); // 24
System.out.println(monthAsText); // 04
System.out.println(yearAsText); // 2014

By the way, why do you want to extract the textual components (leading to a lot of extra formatting work - see my code), not just the parsed integer values? Or have I misunderstood you?

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top