3

I want to build a date widget for a form, which has a select list of months, days, years. since the list is different based on the month and year, i cant hard code it to 31 days. (e.g february has 28 days not 30 or 31 and some years even 29 days) How can I use the calendar or joda object to build me these lists.

JodaStephen
  • 60,927
  • 15
  • 95
  • 117
giladbu
  • 2,839
  • 2
  • 19
  • 14

5 Answers5

3

I strongly recommend that you avoid the built-in date and time APIs in Java.

Instead, use Joda Time. This library is similar to the one which will (hopefully!) make it into Java 7, and is much more pleasant to use than the built-in API.

Now, is the basic problem that you want to know the number of days in a particular month?

EDIT: Here's the code (with a sample):

import org.joda.time.*;
import org.joda.time.chrono.*;

public class Test   
{
    public static void main(String[] args)
    {        
        System.out.println(getDaysInMonth(2009, 2));
    }

    public static int getDaysInMonth(int year, int month)
    {
        // If you want to use a different calendar system (e.g. Coptic)
        // this is the code to change.
        Chronology chrono = ISOChronology.getInstance();
        DateTimeField dayField = chrono.dayOfMonth();        
        LocalDate monthDate = new LocalDate(year, month, 1);
        return dayField.getMaximumValue(monthDate);
    }
}
JodaStephen
  • 60,927
  • 15
  • 95
  • 117
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • Is that relevant? I.e. will that help him build a date widget? – Michael Myers Mar 20 '09 at 21:40
  • @mmyers: Absolutely. Once we've fully identified what he's trying to do, if he does it all with Joda Time it will end up being a lot simpler, I believe. – Jon Skeet Mar 20 '09 at 21:43
  • @Jon. Very good comment indeed. Not so sure about this as an "answer" – OscarRyz Mar 20 '09 at 21:46
  • It'll turn into a proper answer when I've found out the way to get the relevant information from Joda Time. I'm positive it's in here somewhere :) – Jon Skeet Mar 20 '09 at 21:47
  • joda-time, the standard answer of all Java date/time questions. In fact, Jon, you could add a simple if(currentQ.tags.contains("java") && currentQ.tags.contains("calendar")) { addWikiAnswer("Use joda-time"); lockQuestion(currentQ); } to SO's code... – Esko Mar 20 '09 at 21:58
  • @Esko: Yup. It should certainly be part of the answer to all questions asking for help using the built-in API, unless it specifically states why Joda Time is not an option. The more work I do with date/time data, the scarier the whole topic becomes - and the more thankful I become for Joda Time. – Jon Skeet Mar 20 '09 at 22:05
1

tl;dr

int lengthOfMonth = 
    YearMonth.from( 
                      LocalDate.now( ZoneId.of( "America/Montreal" ) ) 
                  )
             .lengthOfMonth() ;

java.time

The Answer by Jon Skeet is correct but now outdated. The Joda-Time project is now in maintenance mode, with the team advising migration to the java.time classes.

LocalDate

The code in java.time is similar to that of Joda-Time, with a LocalDate class. The LocalDate class represents a date-only value without time-of-day and without time zone.

A time zone is crucial in determining a date. For any given moment, the date varies around the globe by zone. For example, a few minutes after midnight in Paris France is a new day while still “yesterday” in Montréal Québec.

ZoneId z = ZoneId.of( “America/Montreal” );
LocalDate today = LocalDate.now( z );

You may interrogate for each part, year number, month, etc. Note that months are number sanely, 1-12 for January-December (unlike in the legacy classes).

int year = today.getYear();
int monthNumber = today.getMonthValue(); // 1-12 for January-December.
int dayOfMonth = today.getDayOfMonth();

You can assemble a LocalDate object from those parts.

LocalDate ld = LocalDate.of( year , monthNumber , dayOfMonth );

YearMonth

To ask for the length of the month, use the YearMonth class.

YearMonth ym = YearMonth.from( ld );
int lengthOfMonth = ym.lengthOfMonth();

About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old date-time classes such as java.util.Date, .Calendar, & java.text.SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to java.time.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations.

Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport and further adapted to Android in ThreeTenABP (see How to use…).

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

Community
  • 1
  • 1
Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
0

Here is an example of creating a list of months:

String[] months = new DateFormatSymbols().getMonths();
    List<String> allMonths = new ArrayList<String>();
    for(String singleMonth: months){
        allMonths.add(singleMonth);
    }
    System.out.println(allMonths);
apajak
  • 21
  • 4
0

The Calendar object will tell you the number of days in the current month using getActualMaximum(Calendar.DAY_OF_MONTH). See an example here.

From that you can update your lists on each change.

Michael Brewer-Davis
  • 14,018
  • 5
  • 37
  • 49
0

There are a number of date picker implementations out there for java, which can be used via swing or a web ui. I would attempt to reuse one of these and avoid writing your own.

emeraldjava
  • 10,894
  • 26
  • 97
  • 170