0

I am creating a project in which I am supposed to take date of birth of any person. So for that I have taken 3 combo boxes: date, month and year. But how I will know that the Date which is going to be inserted is valid because the number of day is different-different months and years is different.

And is there any ready made GUI component for taking dates from users?

I am designing using Swing package.

My sample code is

import java.awt.*;
import javax.swing.*;

public class Pro1 extends JFrame
{

    JComboBox  dd, mm, yy;

    JLabel doblbl;

    Container con;

    public Pro1()
    {
        con = getContentPane(); 

        doblbl = new JLabel("Date of Birth :-");
        doblbl.setHorizontalAlignment(SwingConstants.CENTER);   

        doblbl.setFont(new Font("Arial",Font.BOLD,17));
        doblbl.setForeground(Color.blue);

        doblbl.setOpaque(true); 
        doblbl.setBackground(new Color(230,180,230));


        dd = new JComboBox();
        mm = new JComboBox();
        yy = new JComboBox();

        for(int i = 1; i<=31; i++)
            dd.addItem("" + i);

        for(int i = 1; i<=12; i++)
            mm.addItem("" + i);

        for(int i = 1960; i<=2014; i++)
            yy.addItem("" + i);


        con.setLayout(null); 

        setDefaultCloseOperation(EXIT_ON_CLOSE);    

        int i = 120;

        doblbl.setBounds(30,i+=40,270,30);

        int j = 120;

        dd.setBounds(350,j+=40,50,30);
        mm.setBounds(420,j,50,30);
        yy.setBounds(480,j,70,30);

        con.add(doblbl);

        con.add(dd);
        con.add(mm);
        con.add(yy);

        setSize(1500,800);
        setVisible(true);

        con.setBackground(new Color(125,80,140));           
    }

    public static void main(String s[])
    {
        Pro1 p1 = new Pro1();

    }
}
M. A. Kishawy
  • 5,001
  • 11
  • 47
  • 72

3 Answers3

2

You can use SimpleDateFormat to parse or format the date as dd/MM/yyyy.

Sample code:

SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
String dateString = "30/02/2014"; // form date string in above format

String formattedDate = sdf.format(sdf.parse(dateString));
if (formattedDate.equals(dateString)) {
    System.out.println("valid date");
} else {
    System.out.println("Invalid date"); // It's an invalid date
}
Braj
  • 46,415
  • 5
  • 60
  • 76
  • but if user will enter "30th" date in "feb" then how this code will handle it? – NARSINGH CHARAN Oct 06 '14 at 12:30
  • 2 extra days will be shifted to next Month. `sdf.parse(dateString)` will result into `2 March 2014` and that is not equal to `30 Feb 2014` – Braj Oct 06 '14 at 12:31
  • Just run the program and print the `formattedDate` value – Braj Oct 06 '14 at 12:32
  • The trick here is, that you parse it back into the format the was expected. If it results in the same String, then there was no shift (as in your example of Feb 30). However, you also need to catch exception, as the user might input `"bla"` as the day, which would result in an exception. – brimborium Oct 06 '14 at 12:34
  • 1
    @brimborium The date is selected from combo box so there is no chance of any string input – Braj Oct 06 '14 at 12:36
  • @Braj I see. If you have to select anyway, why don't you use a calendar picker in the first place? There are some pretty neat ones around and they make it impossible to pick an invalid date. – brimborium Oct 06 '14 at 12:38
2

Consider offering the user a JSpinner with a SpinnerDateModel, then it is easier for the user to enter, or scroll through and select, a valid date.

enter image description here

import java.awt.*;
import java.util.*;
import javax.swing.*;

public class PromptForDate {

    public static void main(String[] args) {
        Runnable r = new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(
                            UIManager.getSystemLookAndFeelClassName());
                } catch (Exception useDefault) {}
                SpinnerDateModel dateModel = new SpinnerDateModel(
                        new Date(), null, null, Calendar.DAY_OF_MONTH );
                JSpinner dateSpinner = new JSpinner(dateModel);
                dateSpinner.setEditor(
                        new JSpinner.DateEditor(dateSpinner, "dd/MM/yyyy"));

                JOptionPane.showMessageDialog(
                        null, dateSpinner, "D.O.B.?", 
                        JOptionPane.QUESTION_MESSAGE);

                System.out.println(dateModel.getValue());
            }
        };
        SwingUtilities.invokeLater(r);
    }
}
Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
1

And is there any ready made GUI component for taking dates from users?

Yes, there are several options in standard API and third-party libraries, as exposed in this answer: JSpinner + SpinnerDateModel or JCalendar or JXDatePicker. These components will also solve this other problem:

But how i will know that the date which is going to be inserted is valid because the number of dates in different-different months and years is different.


Off-topic

About this:

con.setLayout(null);
...
dd.setBounds(350,j+=40,50,30);
mm.setBounds(420,j,50,30);
yy.setBounds(480,j,70,30);
...
con.add(dd);
con.add(mm);
con.add(yy);

While using Null layout is perfectly possible, Swing is designed to be used along with layout managers and thus null layout is discouraged. See this topic Why is it frowned upon to use a null layout in SWING?.

Community
  • 1
  • 1
dic19
  • 17,821
  • 6
  • 40
  • 69