0

Quick Background:

I have created a GUI for a reservation application in Eclipse. On it, I have multiple combo boxes for arrival and departure dates (month, day, year - for both). I have retrieved the information and tied it to a String variable so it appears as something like this: 12/04/2014.

The Questions:

  1. What is a good way to convert that string (arrival/departure) to Date datetype for comparison purposes? I will need to verify the arrival is not before today's date and get the length of stay.
  2. What is a good way to retrieve today's date like so - 2/19/2014.

I have been searching the internet for quite a while but can't seem to find anything clear.

Please do not recommend any add-ons or interface tools as I must code this all by hand with only what is readily available (if that makes sense).

Thank you!

--- EDITS ---

I have tried many of the things mentioned below ...

  1. 'Date today = new Date()' gives me a red line under new Date() asking for an argument of int or long.

  2. Below is the code I have when I assemble my date from the combo boxes. dateFormat.parse(holder) gets a red underline prompting to add throws declaration or surround with try/catch. The datatypes for the variables below are ... index (int). holder (String). arrival/departure (java.util.Date) -- for whatever reason it won't accept Date even with that imported, although it does in my Hotel class. Strange, yes, but not my main focus.

        // Assignments
    index = view.getArriveMonthIndex() + 1; // Arrival date
    holder = index + "/" + view.getArriveDay() + "/" + view.getArriveYear();
    arrival = dateFormat.parse(holder);
    
    index = view.getDepartMonthIndex() + 1; // Departure date
    holder = index + "/" + view.getDepartDay() + "/" + view.getDepartYear();
    departure = dateFormat.parse(holder);
    

Something else to perhaps mention/show .. at the very beginning of my class, this is a bit of what I have been playing around with/tried.

DateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy", Locale.US);
Calendar todaysDate = Calendar.getInstance();
String today = dateFormat.format(todaysDate.getTime());

^^ Just tested this last part, it works.

I went ahead with the underlined suggestions for my arrive/departure variables. My method now throws a ParseException. Haven't been able to locate a good description for this - what exactly is its point? (very much new if you couldn't tell) -- BACKUP. Changing that back to how it is above. This way requires a throw/catch around my call to the reserveHotel() method.

mallorz
  • 55
  • 1
  • 8
  • 1
    You should be using the raw `Date` object as the data to the models in of your UI components and using renderers to display the value of the data, preferrably that honours the locale of the user. Today's date is as simple as `new Date()` – MadProgrammer Feb 20 '14 at 01:45
  • See: http://stackoverflow.com/questions/7034781/convert-string-dates-into-java-date-objects – indivisible Feb 20 '14 at 01:47
  • I've gotten the same code - dateFormat.parse(stringDate) - see above. It does not work, however. Am I doing something wrong? – mallorz Feb 20 '14 at 13:35
  • Date does not require parameters - see http://docs.oracle.com/javase/6/docs/api/java/util/Date.html#Date() Make sure you are not using java.sql.Date – Scary Wombat Feb 21 '14 at 08:10
  • see my answer, it gives you what you need. – Scary Wombat Feb 21 '14 at 08:13

4 Answers4

1

You should be using the raw Date object as the data to the models in your UI components and using renderers to display the value of the data, preferably that honours the locale of the user.

This way, you should never have to convert between data types

Take a closer look at How to Use Combo Boxes for more details

For example...

List of dates

import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.EventQueue;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.DateFormat;
import java.util.Calendar;
import java.util.Date;
import javax.swing.DefaultComboBoxModel;
import javax.swing.DefaultListCellRenderer;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class TestCombos {

    public static void main(String[] args) {
        new TestCombos();
    }

    public TestCombos() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                }

                DefaultComboBoxModel model = new DefaultComboBoxModel();
                Calendar cal = Calendar.getInstance();
                for (int index = 0; index < 100; index++) {
                    model.addElement(cal.getTime());
                    cal.add(Calendar.DATE, 1);
                }

                JComboBox comboBox = new JComboBox(model);
                comboBox.setRenderer(new DefaultListCellRenderer(){
                    @Override
                    public Component getListCellRendererComponent(JList<?> list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
                        if (value instanceof Date) {
                            value = DateFormat.getDateInstance(DateFormat.SHORT).format((Date)value);
                        }
                        return super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
                    }
                });
                comboBox.addActionListener(new ActionListener() {
                    @Override
                    public void actionPerformed(ActionEvent e) {
                        Object value = ((JComboBox)e.getSource()).getSelectedItem();
                        if (value instanceof Date) {
                            System.out.println("You have selected a Date value of " + value);
                        } else {
                            System.out.println("You selected something else");
                        }
                    }
                });

                JFrame frame = new JFrame("Testing");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.setLayout(new GridBagLayout());
                frame.add(comboBox);
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

}

Today's date is as simple as new Date()

MadProgrammer
  • 343,457
  • 22
  • 230
  • 366
1

try using the SimpleDateFormat class to specify your date mask ("MM/dd/yyyy") and to convert/parse your string to a Date.

Then compare to a Date created as Date dt = new Date ();

See http://docs.oracle.com/javase/6/docs/api/java/util/Date.html#after(java.util.Date)

Scary Wombat
  • 44,617
  • 6
  • 35
  • 64
0

You can use the following to parse your string into a Date:

Date date = new SimpleDateFormat("MMMM d, yyyy", Locale.ENGLISH).parse(YOURDATE);

You can use the following to get today's date:

Date date = new Date();
ltalhouarne
  • 4,586
  • 2
  • 22
  • 31
0

Use a java SimpleDateFormat like this:

SimpleDateFormat simpleDateFormat = new SimpleDateFormat("MM/dd/yyyy");
String dateString = "12/04/2014";
Date myDate = simpleDateFormat.parse(dateString);

Today's date can just be gotten by doing:

Date today = new Date();
stiemannkj1
  • 4,418
  • 3
  • 25
  • 45