Pergunta

I have this simple piece o code :

DateTimeFormatter format = DateTimeFormat.forPattern("YYYY MM DD");
DateTime dateTime;

String buffer = "2013 01 01";
dateTime = format.parseDateTime(buffer);
System.out.println(dateTime.getMonthOfYear());

buffer = "2013 02 01";
dateTime = format.parseDateTime(buffer);
System.out.println(dateTime.getMonthOfYear());

and output is: 1 1

but I would expect: 1 2

...where is the problem? I don't need to get month of year, but I have problem with determining dayOfWeek, because dateTime has always January and not other months.

Foi útil?

Solução 2

If I understand you need to check your pattern:

DateTimeFormatter format = DateTimeFormat.forPattern("yyyy MM dd");

where

y       year
d       day of month

Outras dicas

The solution given by @LuS is correct. I deliver the explanation.

The choice between the symbols Y (year-of-era in JodaTime) or y (proleptic iso-year) is not so important in your case because in our modern times both years have identical numbers. The symbol M is correct (for month-of-year). So let's concentrate on DD versus dd.

The solution 'd' works because the combination of year/month/day-of-month gives the parser to calculate a calendar date (trivial). If day-of-month is missing then the parser can no longer construct a date just with year and month.

So what is D? It is the day-of-year. Since the corresponding numerical part of the string to be parsed is in both cases "01", the parser constructs the date as ISO-Ordinal-Date with year and day-of-year (both are same in your two examples), ignoring the (differing) month part.

Of course, the parsed result "2013-001" = "2013-01-01" does not fit with input "2013 02 01", so in strict parsing this should fail. Unfortunately JodaTime does not make a try to check the consistency of parsing informations even in strict mode (tested with org.joda.time.chrono.StrictChronology).

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top