I am creating a workaround to fix the SimpleDateFormat "clone" class of CN1 in my app.
I cannot use other classes from pure Java.
I used this instruction in my CN1 app
int dayNumber=c.get(Calendar.DAY_OF_WEEK);
for handling the u letter in the format string.
At the time of the creation of this post it's Wednesday
dayNumber happens to have value of 4.
So I replaced that instruction with
int dayNumber=c.get(Calendar.DAY_OF_WEEK)-1;
because I found in Oracle documentation
Day number of week (1 = Monday, ..., 7 = Sunday)
I would like to know if it is correct
so that I have the 7 days of the week covered so it is just as
(1 = Monday, ..., 7 = Sunday)
and I can have the right u value for Java and Android compatibility.
I understand that java.time, the modern Java date and time API, is not yet part of CodeName One, and that therefore you cannot use it in your case. Apart from special situations like yours no one should use Calendar since it is poorly designed and long outdated. Everyone should use java.time.
To get (1 = Monday, ..., 7 = Sunday) from Calendar (the numbers that you would get by default from java.time):
int dayNumber = (c.get(Calendar.DAY_OF_WEEK) + 5) % 7 + 1;
Seen under modulo 7 I am first adding 5, then 1, so 6 in total, which is the same as subtracting 1. I am using this trickery to make sure I get a number in the 1 through 7 interval (which we don’t always by simply subtracting 1 from the return value from Calendar).
I am demonstrating the edge cases and using java.time for it:
LocalDate ld = LocalDate.of(2021, Month.SEPTEMBER, 5);
ZonedDateTime startOfDay = ld.atStartOfDay(ZoneId.of("Etc/UTC"));
Calendar c = GregorianCalendar.from(startOfDay);
int dayNumber = (c.get(Calendar.DAY_OF_WEEK) + 5) % 7 + 1;
System.out.format("%s: %s = %d%n", ld, ld.getDayOfWeek(), dayNumber);
ld = ld.plusDays(1);
startOfDay = ld.atStartOfDay(ZoneId.of("Etc/UTC"));
c = GregorianCalendar.from(startOfDay);
dayNumber = (c.get(Calendar.DAY_OF_WEEK) + 5) % 7 + 1;
System.out.format("%s: %s = %d%n", ld, ld.getDayOfWeek(), dayNumber);
Output is:
2021-09-05: SUNDAY = 7
2021-09-06: MONDAY = 1
Disclaimer: I don’t know the CodeName One Calendar in particular. I strongly expect it to behave exactly the same as the original java.util.Calendar, and my answer is based on the assumption that it does.
Related
I need to get the 4-5-4 Calendar Week from a Date. Is there any utility like Georgian Calendar in Java for 4-5-4 Retail Calendar?
If not, how can I create one? What all logic is needed? What is 53rd Week in case of Leap Year?
For example, if I pass a date (DD-MM-YYY) 04-03-2018 as input I should get March Week 1 as output.
Or, if I give 01-04-2018 as input I should get March Week 5 as output.
Please help me by providing a way to build this utility.
The following class should do it:
public class NrfMonthWeek {
public static NrfMonthWeek getWeek(LocalDate date) {
// Determine NRF calendar year.
// The year begins on the Sunday in the interval Jan 29 through Feb 4.
LocalDate firstDayOfNrfYear = date.with(MonthDay.of(Month.JANUARY, 29))
.with(TemporalAdjusters.nextOrSame(DayOfWeek.SUNDAY));
if (date.isBefore(firstDayOfNrfYear)) { // previous NRF year
firstDayOfNrfYear = date.minusYears(1)
.with(MonthDay.of(Month.JANUARY, 29))
.with(TemporalAdjusters.nextOrSame(DayOfWeek.SUNDAY));
}
// 1-based week of NRF year
int weekOfNrfYear = (int) ChronoUnit.WEEKS.between(firstDayOfNrfYear, date) + 1;
assert 1 <= weekOfNrfYear && weekOfNrfYear <= 53 : weekOfNrfYear;
YearMonth firstMonthOfNrfYear = YearMonth.from(firstDayOfNrfYear)
.with(Month.FEBRUARY);
if (weekOfNrfYear == 53) {
// Special case: the last week of a 53 weeks year belongs to
// the last month, January; this makes it a 5 weeks month.
return new NrfMonthWeek(firstMonthOfNrfYear.plusMonths(11), 5);
} else {
// 1-based month of NRF year (1 = February through 12 = January).
// A little math trickery to make the 4-5-4 pattern real.
int monthOfNrfYear = (weekOfNrfYear * 3 + 11) / 13;
// Number of weeks before the NRF month: 0 for February, 4 for March, 9 for April, etc.
int weeksBeforeMonth = (monthOfNrfYear * 13 - 12) / 3;
int weekOfMonth = weekOfNrfYear - weeksBeforeMonth;
return new NrfMonthWeek(
firstMonthOfNrfYear.plusMonths(monthOfNrfYear - 1), weekOfMonth);
}
}
private YearMonth month;
/** 1 through 5 */
private int weekOfMonth;
public NrfMonthWeek(YearMonth month, int weekOfMonth) {
this.month = Objects.requireNonNull(month);
if (weekOfMonth < 1 || weekOfMonth > 5) {
throw new IllegalArgumentException("Incorrect week number " + weekOfMonth);
}
this.weekOfMonth = weekOfMonth;
}
#Override
public String toString() {
return month.getMonth().getDisplayName(TextStyle.FULL, Locale.US)
+ " Week " + weekOfMonth;
}
}
Let’s try it. Here I pass the two dates from your question to the getWeek method:
System.out.println(NrfMonthWeek.getWeek(LocalDate.of(2018, Month.MARCH, 4)));
System.out.println(NrfMonthWeek.getWeek(LocalDate.of(2018, Month.APRIL, 1)));
This prints the desired:
March Week 1
March Week 5
Though only month and week are printed, also the year is contained in the object returned from getWeek.
The formulas for calculating the month and week-of-month are cryptic. I have no really good argument why they work, though such an argument could probably be constructed. I have tested them with all relevant values, and you are free to do the same. Other than that, using java.time, the modern Java date and time API, it wasn’t too bad.
If that were me, I would have finer validation in the NrfMonthWeek constructor, only allowing week 5 in the months that may have 5 weeks. I am leaving that to you. And I would have a pretty thorough unit test.
Please check whether my understanding agrees with yours: If I have understood correctly from the example calendars that Basil Bourque linked to in his answer, the NRF 4-5-4 year starts with February. Its weeks begin on Sunday, and the first week of the year is the first week that contains at least 4 days of February. In other words, the week that contains February 4. In yet other words, the week that begins on a Sunday in the interval January 29 through February 4. Months March, June, September and December always have 5 weeks. In case of a 53 weeks year also January has 5 weeks.
No support built-in
Neither the modern java.time classes nor the legacy date-time classes (Date/Calendar) directly support the National Retail Federation 4-5-4 Calendar.
Implement Chronology
I suspect the best way to solve this problem is to implement a Chronology for the java.time framework.
Java 8 and later bundle five implementations (HijrahChronology, IsoChronology, JapaneseChronology, MinguoChronology, ThaiBuddhistChronology). Their source is available in the OpenJDK project.
The ThreeTen-Extra project provides ten more chronologies (AccountingChronology, BritishCutoverChronology, CopticChronology, DiscordianChronology, EthiopicChronology, InternationalFixedChronology, JulianChronology, PaxChronology, Symmetry010Chronology, Symmetry454Chronology) whose source code might help.
This question already has answers here:
What would be a good implementation to get all Monday and Thursday dates Between a given date range (DateX and DateY) in JAVA
(3 answers)
Closed 5 years ago.
Can someone suggest the logic to find out the no. of Mondays between two dates in Java?
Instead of looping through all the days, is there any other approach to count the no. of occurrences of Mondays between two dates in java
There’s more than one way to go. Here’s a suggestion:
public static long noOfMondaysBetween(LocalDate first, LocalDate last) {
if (last.isBefore(first)) {
throw new IllegalArgumentException("first " + first + " was after last " + last);
}
// find first Monday in interval
LocalDate firstMonday = first.with(TemporalAdjusters.next(DayOfWeek.MONDAY));
// similarly find last Monday
LocalDate lastMonday = last.with(TemporalAdjusters.previous(DayOfWeek.MONDAY));
// count
long number = ChronoUnit.WEEKS.between(firstMonday, lastMonday);
// add one to count both first Monday and last Monday in
return number + 1;
}
For example, noOfMondaysBetween(LocalDate.of(2017, Month.JUNE, 15), LocalDate.of(2017, Month.JUNE, 15)) returns 0. It may be a little subtle that the code takes this case into account: First Monday is June 19 and last is June 12. Count of weeks between the two Mondays is -1, so when I add 1, the result is 0, which is correct. To count the Mondays in June:
System.out.println(noOfMondaysBetween(LocalDate.of(2017, Month.MAY, 31), LocalDate.of(2017, Month.JULY, 1)));
Result:
4
If you intended to include the first date in the count (if it is a Monday), use nextOrSame(DayOfWeek.MONDAY) instead of next(DayOfWeek.MONDAY). Similarly to include the second date use previousOrSame(DayOfWeek.MONDAY).
I'm not a Java coder but I'm a coder. Here's how I'd solve this:
Count the days between the two dates (aka DATESPAN). I'm sure Java has a function for that.
Get the 'Day of Week' (AS A NUMBER, assuming that Monday = 1 )of both dates. I'm sure Java has a function for this too. We need to know if either is a Monday.
If DATESPAN < 7 Use this logic:
Answer = End Date Number > DATESPAN ? 0 : 1
IF DATESPAN >=7 CONTINUE TO GET ANSWER:
Divide the DATESPAN by 7.
If there is a remainder from the division, use the floor value of the quotient for the answer.
If there is NO remainder, check the start date and end date. If either are a Monday the quotient is the answer, If not the quotient - 1 is the answer
I need to find the day of the week (i.e. Monday, Tuesday...) given MM-DD-YYYY. So basically what java calendar would do, but without using java calendar.
It is possible, though unusual, to compute a number that corresponds to the day of the week from a calendar date.
In brief, you will first need to calculate a serial date number from the calendar date, i.e. a number that is a continuous count of days that have elapsed since a certain fixed point in time (informally called 'the epoch'). The most commonly encountered serial date scheme encountered in modern computing is Posix Time, which has an epoch date of Jan 1, 1970 at midnight UTC.
You will need to decide what level of precision is needed for this calculation, eg. whether you will need to account for the Julian Calendar (used in most of Europe before the Gregorian Calendar reform by Pope Gregory in 1584), whether to correct for century days, etc.
Several algorithms are available to arithmetically convert a calendar date to a serial date number with a given epoch. Historically, the most commonly used epoch for these calculations has been the Julian Day number system (not to be confused with the Julian Calendar), which counts days from November 24, 4714 BC in the proleptic Gregorian calendar. Below is Java code which implements one such algorithm published by Jean Meeus in his book "Astronomical Algorithms, 2nd Ed." This algorithm computes a Julian Day number and assumes that days are exactly 86400 seconds in length, accounts for the general Gregorian Reform, and accounts for century and leap days:
public class JulianDay {
private static final int YEAR = 0;
private static final int MONTH = 1;
private static final int DAY = 2;
private static final int HOURS = 3;
private static final int MINUTES = 4;
private static final int SECONDS = 5;
private static final int MILLIS = 6;
:
:
// Converts a timestamp presented as an array of integers in the following
// order (from index 0 to 6): year,month,day,hours,minutes,seconds,millis
// month (1-12), day (1-28 or 29), hours (0-23), min/sec (0-59) to a
// Julian Day Number.
// For clarity and simplicity, the input values are assumed to be well-formed;
// error checking is not implemented in the snippet.
public static double toJD(int[] ymd_hms) {
int y = ymd_hms[YEAR];
int m = ymd_hms[MONTH];
double d = (double) ymd_hms[DAY];
d = d + ((ymd_hms[HOURS] / 24.0) +
(ymd_hms[MINUTES] / 1440.0) +
(ymd_hms[SECONDS] / 86400.0) +
(ymd_hms[MILLIS] / 86400000.0));
if (m == 1 || m == 2) {
y--;
m = m + 12;
}
double a = Math.floor(y / 100);
double b = 2 - a + Math.floor(a / 4);
return (Math.floor(365.25 * (y + 4716.0)) +
Math.floor(30.6001 * (m + 1)) +
d + b - 1524.5);
}
}
Once you have a serial date number, it is straightforward to compute the day of the week from the remainder when the date number is divided by 7 (the number of days in a week).
If you are talking about simply avoiding the Calendar Object then you could use the Date Object (deprecated) but still works and call setMonth, setYear, and setDate to get the desired date. You then have to use a DateFormatter to get your desired output. I used a SimpleDateFormat and the E specifier to get the day of the week.
Date dNow = new Date();
SimpleDateFormat ft = new SimpleDateFormat ("E");
System.out.println("Current Date: " + ft.format(dNow));
This outputs the current day of the week "Sun", "Sat", etc..
This link will help with the formatting https://www.tutorialspoint.com/java/java_date_time.htm
java.time
Using the java.time classes that supplant the troublesome old date-time classes. The LocalDate class represents a date without a time-of-day and without a time zone.
DayOfWeek dow =
LocalDate.parse(
"01-23-2016" ,
DateTimeFormatter.ofPattern( "MM-dd-uuuu" )
).getDayOfWeek()
That code returns a DayOfWeek enum object. From there you can interrogate for:
Integer number, 1-7 for Monday-Sunday
Localized name of the day.
Example code.
int dowNumber = dow.getValue() ;
String dowName = dow.getDisplayName(
TextStyle.FULL ,
Locale.CANADA_FRENCH ) ; // Or Locale.US, Locale.ITALY, etc.
TIP: Pass around the DayOfWeek objects themselves in your own code, rather than internally track the day-of-week as a number or string. This makes your code more self-documenting, ensures valid values, and provides for type-safety.
I was looking for the answer myself and found another answer based on Zeller's algorithm:
// d = day in month
// m = month (January = 1 : December = 12)
// y = 4 digit year
// Returns 0 = Sunday .. 6 = Saturday
public int dow(int d, int m, int y) {
if (m < 3) {
m += 12;
y--;
}
return (d + int((m+1)*2.6) + y + int(y/4) + 6*int(y/100) + int(y/400) + 6) % 7;
}
Source: here
Julian Day Numbers are a means of representing timestamps as a continuous count of days (and fractional days) since noon UTC, January 1, 4713 B.C. The Java 7 SE API does not contain support for this format. Developers who have used the SQLite database may have used the native Julian Day support provided by the strftime() functions.
The advantages of representing timestamps as Julian Day Numbers include:
A date and time can be represented to millisecond precision in a primitive data type (double)
Days in a year are somewhat more concrete than seconds in a day
Circumvents the problem of "leap seconds" if this degree of precision is unimportant
Days between dates arithmetic is trivial; sorting precedence is easily determined
Very lightweight
Disadvantages
The Java Date/Time API does not have built-in support for JDN's
Unsuitable for very precise time measurements
Only defined for UTC and must be mapped from UTC to local time
Unsuitable for display to end-users; must be converted/formatted before display
Julian Day Numbers are commonly used in astronomical calculations and their definition is highly standardized and accepted. Similarly, Modified Julian Day Numbers (which count from midnight UTC, 17 November 1858) are standardly defined and used in aerospace applications (see http://tycho.usno.navy.mil/mjd.html).
For applications that make extensive use of date/time arithmetic or chronological sorting (or if persisting lightweight primitives is more appealing than persisting timestamps), internally representing dates and times as JDN's or MJD's may make sense for you.
The following code defines functions that facilitate using either Julian Day Numbers or Modified Julian Day Numbers with the Java Date/Time/Calendar API. The code is based on algorithms published in Jean Meeus's "Astronomical Algorithms", 1st ed., 1991.
public class JulianDay {
private static final int YEAR = 0;
private static final int MONTH = 1;
private static final int DAY = 2;
private static final int HOURS = 3;
private static final int MINUTES = 4;
private static final int SECONDS = 5;
private static final int MILLIS = 6;
:
:
// Converts a timestamp presented as an array of integers in the following
// order (from index 0 to 6): year,month,day,hours,minutes,seconds,millis
// month (1-12), day (1-28 or 29), hours (0-23), min/sec (0-59) to a
// Modified Julian Day Number.
// For clarity and simplicity, the input values are assumed to be well-formed;
// error checking is not implemented in the snippet.
public static double toMJD(int[] ymd_hms) {
int y = ymd_hms[YEAR];
int m = ymd_hms[MONTH];
double d = (double) ymd_hms[DAY];
d = d + ((ymd_hms[HOURS] / 24.0) +
(ymd_hms[MINUTES] / 1440.0) +
(ymd_hms[SECONDS] / 86400.0) +
(ymd_hms[MILLIS] / 86400000.0));
if (m == 1 || m == 2) {
y--;
m = m + 12;
}
double a = Math.floor(y / 100);
double b = 2 - a + Math.floor(a / 4);
return (Math.floor(365.25 * (y + 4716.0)) +
Math.floor(30.6001 * (m + 1)) +
d + b - 1524.5) - 2400000.5; // for Julian Day omit the 2400000.5 term
}
// Converts an Modified Julian Day Number (double) to an integer array representing
// a timestamp (year,month,day,hours,mins,secs,millis). Works for all positive JDN
public static int[] toTimestamp(double mjd) {
int ymd_hms[] = { -1, -1, -1, -1, -1, -1, -1 };
int a, b, c, d, e, z;
double jd = mjd + 2400000.5 + 0.5; // if a JDN is passed as argument,
// omit the 2400000.5 term
double f, x;
z = (int) Math.floor(jd);
f = jd - z;
if (z >= 2299161) {
int alpha = (int) Math.floor((z - 1867216.25) / 36524.25);
a = z + 1 + alpha - (int) Math.floor(alpha / 4);
} else {
a = z;
}
b = a + 1524;
c = (int) Math.floor((b - 122.1) / 365.25);
d = (int) Math.floor(365.25 * c);
e = (int) Math.floor((b - d) / 30.6001);
ymd_hms[DAY] = b - d - (int) Math.floor(30.6001 * e);
ymd_hms[MONTH] = (e < 14)
? (e - 1)
: (e - 13);
ymd_hms[YEAR] = (ymd_hms[MONTH] > 2)
? (c - 4716)
: (c - 4715);
for (int i = HOURS; i <= MILLIS; i++) {
switch(i) {
case HOURS:
f = f * 24.0;
break;
case MINUTES: case SECONDS:
f = f * 60.0;
break;
case MILLIS:
f = f * 1000.0;
break;
}
x = Math.floor(f);
ymd_hms[i] = (int) x;
f = f - x;
}
return ymd_hms;
}
}
This answer has been provided here as well: How can I convert between a Java Date and Julian day number?. In the current post, references for the algorithm are provided along with some more discussion. The implementation of algorithms above also contains no Java API dependencies (aside from Math functions).
java.time
The java.time framework built into Java 8 and later supplants the old date-time classes bundled with the earliest versions of Java. See Oracle Tutorial. Much of the functionality has been back-ported to Java 6 & 7 in ThreeTen-Backport and further adapted to Android in ThreeTenABP.
The java.time classes include the java.time.temporal.JulianFields. This class provides three implementations of TemporalField to give limited support for Julian date-only values (no time-of-day). So you can get whole number of days, not the double requested in the Question. Read that class doc closely to be sure it behaves to your expectations. Note that unlike most other java.time classes, these Julian classes ignore any offset-from-UTC or time zone information (always treated as a local date).
JULIAN_DAY → Count of whole days since day 0, which is January 1, 4713 BCE in the Julian calendar ( -4713-11-24 Gregorian ).
MODIFIED_JULIAN_DAY → Like JULIAN_DAY but subtracting 2_400_000.5 (basically dropping the first two digits of Julian date number). Note that results here are one fewer (-1) than Julian date number of item above.
RATA_DIE → Similar to the two items above in that it is a count of days from an epoch. But here the epoch is the ISO 8601 date of 0001-01-01.
In this example we start with the ISO 8601 date of 1970-01-01.
LocalDate localDate = LocalDate.of ( 1970 , 1 , 1 );
long julianDate = JulianFields.JULIAN_DAY.getFrom ( localDate );
long modifiedJulianDate = JulianFields.MODIFIED_JULIAN_DAY.getFrom ( localDate );
long rataDie = JulianFields.RATA_DIE.getFrom ( localDate );
localDate: 1970-01-01 | julianDate: 2440588 | modifiedJulianDate: 40587 | rataDie: 719163
ThreeTen-Extra
The ThreeTen-Extra project is the experimental proving grounds for possible future additions to java.time. The name comes from the JSR 310 that defines java.time.
This library includes additional support for Julian dates in its Julian calendar system (Chronology). Like the support in Java 8, this library is limited to date-only values (no partial days or time-of-day).
With this library you can instantiate JulianDate objects.
Many methods and features for you to examine there.
I know that this is not a Java Calendar API, but maybe you should try Jodd tool.
JulianDateStamp julianStamp = new JulianDateStamp(julianDays);
JDateTime jdate = new JDateTime(julianStamp);
Date date = new Date(jdate.getTimeInMillis());
This works perfect for:
2113488,2746855323 -> 1074.06.01 18:35
2453479,5866961805 -> 2005.04.19 02:04
Read more.
If you are willing to move outside the core JDK classes, then Joda can be a solution.
Joda supports the Julian calendar system. From their doc page:
Chronology julianChrono = JulianChronology.getInstance();
DateTime dt = new DateTime(1066, 10, 14, 0, 0, 0, julianChrono);
That would be the Battle of Hastings 1066 in the Julian Calendar system.
I'm not sure what I'm doing wrong, but I've got a piece of code which calculates the number of days between two dates, and which looks something like the following:
final Calendar first = new GregorianCalendar(2010, Calendar.OCTOBER, 1);
final Calendar last = new GregorianCalendar(2010, Calendar.NOVEMBER, 1);
final long difference = last.getTimeInMillis() - first.getTimeInMillis();
final long days = difference / (1000 * 60 * 60 * 24);
System.out.println("difference: " + difference);
System.out.println("days: " + days);
To summarise, the code block above calculates the number of days between 1st October 2010 and 1 November 2010. I'm expecting to see it return 31 days (seeing as there's 31 days in October)
difference: xxxx
days: 31
but instead it's showing 30 days in October!
difference: 2674800000
days: 30
I've managed to narrow it down to between the the dates 2 October 2010 and 3 October 2010, which seems to only have 82800000 milliseconds, instead of a full 86400000 milliseconds (exactly one hour missing).
Does anyone have any ideas what I'm doing wrong? Or is the 2nd October a special date which has one minute less than a regular day?
(86400000 - 82800000)/1000 = 3600, which is one hour. You're seeing daylight savings time, combined with the rounding of integer math
You could get around it by doing the calculations with floating point numbers and rounding at the end, or you could check out a library like Joda time which offers much better date math than what's built in.
You may be better off comparing the year and day or year instead of the milliseconds that pass in a day.
int lastYear= last.get(Calendar.YEAR);
int firstYear= first.get(Calendar.YEAR);
int lastDayofYear = last.get(Calendar.DAY_OF_YEAR);
int firstDayofYear = first.get(Calendar.DAY_OF_YEAR);
int nDaysElapse = lastDayofYear - firstDayofYear;
int nYearsElapse = lastYear- firstYear;
int days = (nYearsElapse*365)+nDaysElapse;
You should read this post to get a better understanding of how Calendar is interrelated with date/time stamps.
Having read that site, my initial questions were:
What do you mean by days? Do you mean '24-hour blocks' or do you mean calendar days? In the same vein, do you care if you are off slightly due to daylight savings etc?
If you mean Calendar days, your best bet is probably to:
final Calendar first = new GregorianCalendar(2010, 9, 1);
final Calendar last = new GregorianCalendar(2010, 10, 1);
Calendar difference = Calendar.getInstance();
difference.setTimeInMillis(last.getTimeInMillis() - first.getTimeInMillis());
int numDays = difference.get(Calendar.DAY_OF_YEAR) - difference.getMinimum(Calendar.DAY_OF_YEAR);
Of course, the above code will only work if the number of days < 365. You will need to create a rolling calculation e.g.
int yearDiff = last.get(Calendar.YEAR) - first.get(Calendar.YEAR);
Calendar tmp = new GregorianCalendar();
tmp.setTimeInMillis(first.getTimeInMillis());
for(int i = 0; i < yearDiff; i++) {
numDays += tmp.getActualMaximum(Calendar.DAY_OF_YEAR);
i++;
tmp.add(Calendar.YEAR, 1);
}
This should allow you to get the number of days in a correct and consistent manner, without worrying about Daylight Savings, Leap Years etc.
That said, JodaTime probably has this functionality built in.
The answer by Brad Mace is correct.
Use a Library
This question is a good example of why you should use a good date-time library wither than roll your own. For Java that means using either Joda-Time or the new java.time package in Java 8.
Joda-Time
Example code in Joda-Time.
DateTimeZone timeZone = DateTimeZone.forID( "Australia/Melbourne" );
DateTime theFirst = new DateTime( 2014, DateTimeConstants.OCTOBER, 1, 0, 0, 0, timeZone ).withTimeAtStartOfDay();
DateTime nextMonth = theFirst.plusMonths( 1 ).withTimeAtStartOfDay();
int days = Days.daysBetween( theFirst, nextMonth ).getDays();
Or if you don't care about time-of-day, use the LocalDate class.
java.time
Java 8 and later comes with a new java.time framework to supplant the old java.util.Date/.Calendar classes. Inspired by Joda-Time, defined by JSR 310, and extended by the ThreeTen-Extra project.
Example code using Java 8. Note that the enum ChronoUnit returns a 64-bit long rather than int.
LocalDate firstOfOctober = LocalDate.of( 2010 , java.time.Month.OCTOBER , 1 );
LocalDate nextMonth = firstOfOctober.plusMonths( 1 );
long daysInMonth = ChronoUnit.DAYS.between( firstOfOctober , nextMonth );
The code you put in your post is calculating the time between September 1 and October 1, not October 1 and November 1. The output is correct for the code you posted.