5.12. Date and Time Input with DateField

The DateField component provides the means to display and input date and time. The field comes in two variations: PopupDateField, with a numeric input box and a popup calendar view, and InlineDateField, with the calendar view always visible. The DateField base class defaults to the popup variation.

The example below illustrates the use of the DateField baseclass, which is equivalent to the PopupDateField. We set the initial time of the date field to current time by using the default constructor of the java.util.Date class.

// Create a DateField with the default style
DateField date = new DateField();

// Set the date and time to present
date.setValue(new Date());

The result is shown in Figure 5.30, “DateField (PopupDateField) for Selecting Date and Time”.

Figure 5.30. DateField (PopupDateField) for Selecting Date and Time

DateField (PopupDateField) for Selecting Date and Time

5.12.1. PopupDateField

The PopupDateField provides date input using a text box for the date and time. As the DateField defaults to this component, the use is exactly the same as described earlier. Clicking the handle right of the date opens a popup view for selecting the year, month, and day, as well as time. Also the Down key opens the popup. Once opened, the user can navigate the calendar using the cursor keys.

The date and time selected from the popup are displayed in the text box according to the default date and time format of the current locale, or as specified with setDateFormat(). The same format definitions are used for parsing user input.

Date and Time Format

The date and time are normally displayed according to the default format for the current locale (see Section 5.3.5, “Locale”). You can specify a custom format with setDateFormat(). It takes a format string that follows the format of the SimpleDateFormat in Java.

// Display only year, month, and day in ISO format
date.setDateFormat("yyyy-MM-dd");

The result is shown in Figure 5.31, “Custom Date Format for PopupDateField.

Figure 5.31. Custom Date Format for PopupDateField

Custom Date Format for PopupDateField

The same format specification is also used for parsing user-input date and time, as described later.

Handling Malformed User Input

A user can easily input a malformed or otherwise invalid date or time. DateField has two validation layers: first on the client-side and then on the server-side.

The validity of the entered date is first validated on the client-side, immediately when the input box loses focus. If the date format is invalid, the v-datefield-parseerror style is set. Whether this causes a visible indication of a problem depends on the theme. The built-in reindeer theme does not shown any indication by default, making server-side handling of the problem more convenient.

.mydate.v-datefield-parseerror .v-textfield {
    background: pink;
}

The setLenient(true) setting enables relaxed interpretation of dates, so that invalid dates, such as February 30th or March 0th, are wrapped to the next or previous month, for example.

The server-side validation phase occurs when the date value is sent to the server. If the date field is set in immediate state, it occurs immediately after the field loses focus. Once this is done and if the status is still invalid, an error indicator is displayed beside the component. Hovering the mouse pointer over the indicator shows the error message.

You can handle the errors by overriding the handleUnparsableDateString() method. The method gets the user input as a string parameter and can provide a custom parsing mechanism, as shown in the following example.

// Create a date field with a custom parsing and a
// custom error message for invalid format
PopupDateField date = new PopupDateField("My Date") {
    @Override
    protected Date handleUnparsableDateString(String dateString)
    throws Property.ConversionException {
        // Try custom parsing
        String fields[] = dateString.split("/");
        if (fields.length >= 3) {
            try {
                int year  = Integer.parseInt(fields[0]);
                int month = Integer.parseInt(fields[1])-1;
                int day   = Integer.parseInt(fields[2]);
                GregorianCalendar c =
                    new GregorianCalendar(year, month, day);
                return c.getTime();
            } catch (NumberFormatException e) {
                throw new Property.
                    ConversionException("Not a number");
            }
        }
        
        // Bad date
        throw new Property.
            ConversionException("Your date needs two slashes");
    }
};
        
// Display only year, month, and day in slash-delimited format
date.setDateFormat("yyyy/MM/dd");

// Don't be too tight about the validity of dates
// on the client-side
date.setLenient(true);

The handler method must either return a parsed Date object or throw a ConversionException. Returning null will set the field value to null and clear the input box.

Customizing the Error Message

In addition to customized parsing, overriding the handler method for unparseable input is useful for internationalization and other customization of the error message. You can also use it for another way for reporting the errors, as is done in the example below:

// Create a date field with a custom error message for invalid format
PopupDateField date = new PopupDateField("My Date") {
    @Override
    protected Date handleUnparsableDateString(String dateString)
    throws Property.ConversionException {
        // Have a notification for the error
        Notification.show(
                "Your date needs two slashes",
                Notification.TYPE_WARNING_MESSAGE);
        
        // A failure must always also throw an exception
        throw new Property.ConversionException("Bad date");
    }
};

If the input is invalid, you should always throw the exception; returning a null value would make the input field empty, which is probably undesired.

Input Prompt

Like other fields that have a text box, PopupDateField allows an input prompt that is visible until the user has input a value. You can set the prompt with setInputPrompt.

PopupDateField date = new PopupDateField();

// Set the prompt
date.setInputPrompt("Select a date");
        
// Set width explicitly to accommodate the prompt
date.setWidth("10em");

The date field doesn't automatically scale to accommodate the prompt, so you need to set it explicitly with setWidth().

The input prompt is not available in the DateField superclass.

CSS Style Rules

.v-datefield, v-datefield-popupcalendar {}
.v-textfield, v-datefield-textfield {}
.v-datefield-button {}

The top-level element of DateField and all its variants have v-datefield style. The base class and the PopupDateField also have the v-datefield-popupcalendar style.

In addition, the top-level element has a style that indicates the resolution, with v-datefield- basename and an extension, which is one of full, day, month, or year. The -full style is enabled when the resolution is smaller than a day. These styles are used mainly for controlling the appearance of the popup calendar.

The text box has v-textfield and v-datefield-textfield styles, and the calendar button v-datefield-button.

Once opened, the calendar popup has the following styles at the top level:

.v-datefield-popup {}
  .v-popupcontent {}
    .v-datefield-calendarpanel {}

The top-level element of the floating popup calendar has .v-datefield-popup style. Observe that the popup frame is outside the HTML structure of the component, hence it is not enclosed in the v-datefield element and does not include any custom styles. The content in the v-datefield-calendarpanel is the same as in InlineDateField, as described in Section 5.12.2, “InlineDateField.

5.12.2. InlineDateField

The InlineDateField provides a date picker component with a month view. The user can navigate months and years by clicking the appropriate arrows. Unlike with the popup variant, the month view is always visible in the inline field.

// Create a DateField with the default style
InlineDateField date = new InlineDateField();
    
// Set the date and time to present
date.setValue(new java.util.Date());

The result is shown in Figure 5.32, “Example of the InlineDateField.

Figure 5.32. Example of the InlineDateField

Example of the InlineDateField

The user can also navigate the calendar using the cursor keys.

CSS Style Rules

.v-datefield {}
  .v-datefield-calendarpanel {}
    .v-datefield-calendarpanel-header {}
      .v-datefield-calendarpanel-prevyear {}
      .v-datefield-calendarpanel-prevmonth {}
      .v-datefield-calendarpanel-month {}
      .v-datefield-calendarpanel-nextmonth {}
      .v-datefield-calendarpanel-nextyear {}
    .v-datefield-calendarpanel-body {}
      .v-datefield-calendarpanel-weekdays,
      .v-datefield-calendarpanel-weeknumbers {}
        .v-first {}
        .v-last {}
      .v-datefield-calendarpanel-weeknumber {}
      .v-datefield-calendarpanel-day {}
    .v-datefield-calendarpanel-time {}
      .v-datefield-time {}
        .v-select {}
        .v-label {}

The top-level element has the v-datefield style. In addition, the top-level element has a style name that indicates the resolution of the calendar, with v-datefield- basename and an extension, which is one of full, day, month, or year. The -full style is enabled when the resolution is smaller than a day.

The v-datefield-calendarpanel-weeknumbers and v-datefield-calendarpanel-weeknumber styles are enabled when the week numbers are enabled. The former controls the appearance of the weekday header and the latter the actual week numbers.

The other style names should be self-explanatory. For weekdays, the v-first and v-last styles allow making rounded endings for the weekday bar.

5.12.3. Time Resolution

The DateField displays dates by default. It can also display the time in hours and minutes, or just the month or year. The visibility of the input components is controlled by time resolution, which can be set with setResolution() method. The method takes as its parameters the lowest visible component, typically DateField.Resolution.DAY for just dates and DateField.Resolution.MIN for dates with time in hours and minutes. Please see the API Reference for the complete list of resolution parameters.

5.12.4. DateField Locale

The date and time are displayed according to the locale of the user, as reported by the browser. You can set a custom locale with the setLocale() method of AbstractComponent, as described in Section 5.3.5, “Locale”. Only Gregorian calendar is supported.

Preface
I. Introduction
1. Introduction
1.1. Overview
1.2. Example Application Walkthrough
1.3. Support for the Eclipse IDE
1.4. Goals and Philosophy
1.5. Background
2. Getting Started with Vaadin
2.1. Overview
2.2. Setting up the Development Environment
2.3. Overview of Vaadin Libraries
2.4. Installing Vaadin Plugin for Eclipse
2.5. Creating and Running a Project with Eclipse
2.6. Using Vaadin with Maven
2.7. Creating a Project with NetBeans IDE
2.8. Creating a Project with IntelliJ IDEA
2.9. Vaadin Installation Package
2.10. Using Vaadin with Scala
3. Architecture
3.1. Overview
3.2. Technological Background
3.3. Client-Side Engine
3.4. Events and Listeners
II. Server-Side Framework
4. Writing a Server-Side Web Application
4.1. Overview
4.2. Building the UI
4.3. Handling Events with Listeners
4.4. Images and Other Resources
4.5. Handling Errors
4.6. Notifications
4.7. Application Lifecycle
4.8. Deploying an Application
5. User Interface Components
5.1. Overview
5.2. Interfaces and Abstractions
5.3. Common Component Features
5.4. Field Components
5.5. Component Extensions
5.6. Label
5.7. Link
5.8. TextField
5.9. TextArea
5.10. PasswordField
5.11. RichTextArea
5.12. Date and Time Input with DateField
5.13. Button
5.14. CheckBox
5.15. Selecting Items
5.16. Table
5.17. Tree
5.18. MenuBar
5.19. Embedded Resources
5.20. Upload
5.21. ProgressBar
5.22. Slider
5.23. Calendar
5.24. Component Composition with CustomComponent
5.25. Composite Fields with CustomField
6. Managing Layout
6.1. Overview
6.2. UI, Window, and Panel Content
6.3. VerticalLayout and HorizontalLayout
6.4. GridLayout
6.5. FormLayout
6.6. Panel
6.7. Sub-Windows
6.8. HorizontalSplitPanel and VerticalSplitPanel
6.9. TabSheet
6.10. Accordion
6.11. AbsoluteLayout
6.12. CssLayout
6.13. Layout Formatting
6.14. Custom Layouts
7. Visual User Interface Design with Eclipse
7.1. Overview
7.2. Creating a New Composite
7.3. Using The Visual Editor
7.4. Structure of a Visually Editable Component
8. Themes
8.1. Overview
8.2. Introduction to Cascading Style Sheets
8.3. Syntactically Awesome Stylesheets (Sass)
8.4. Creating and Using Themes
8.5. Creating a Theme in Eclipse
8.6. Responsive Themes
9. Binding Components to Data
9.1. Overview
9.2. Properties
9.3. Holding properties in Items
9.4. Creating Forms by Binding Fields to Items
9.5. Collecting Items in Containers
10. Vaadin SQLContainer
10.1. Architecture
10.2. Getting Started with SQLContainer
10.3. Filtering and Sorting
10.4. Editing
10.5. Caching, Paging and Refreshing
10.6. Referencing Another SQLContainer
10.7. Using FreeformQuery and FreeformStatementDelegate
10.8. Non-implemented methods of Vaadin container interfaces
10.9. Known Issues and Limitations
11. Advanced Web Application Topics
11.1. Handling Browser Windows
11.2. Embedding UIs in Web Pages
11.3. Debug Mode and Window
11.4. Request Handlers
11.5. Shortcut Keys
11.6. Printing
11.7. Google App Engine Integration
11.8. Common Security Issues
11.9. Navigating in an Application
11.10. Advanced Application Architectures
11.11. Managing URI Fragments
11.12. Drag and Drop
11.13. Logging
11.14. JavaScript Interaction
11.15. Accessing Session-Global Data
11.16. Server Push
12. Portal Integration
12.1. Overview
12.2. Creating a Portlet Project in Eclipse
12.3. Portlet UI
12.4. Deploying to a Portal
12.5. Installing Vaadin in Liferay
12.6. Handling Portlet Requests
12.7. Handling Portlet Mode Changes
12.8. Non-Vaadin Portlet Modes
12.9. Vaadin IPC for Liferay
III. Client-Side Framework
13. Client-Side Vaadin Development
13.1. Overview
13.2. Installing the Client-Side Development Environment
13.3. Client-Side Module Descriptor
13.4. Compiling a Client-Side Module
13.5. Creating a Custom Widget
13.6. Debugging Client-Side Code
14. Client-Side Applications
14.1. Overview
14.2. Client-Side Module Entry-Point
14.3. Compiling and Running a Client-Side Application
14.4. Loading a Client-Side Application
15. Client-Side Widgets
15.1. Overview
15.2. GWT Widgets
15.3. Vaadin Widgets
16. Integrating with the Server-Side
16.1. Overview
16.2. Starting It Simple With Eclipse
16.3. Creating a Server-Side Component
16.4. Integrating the Two Sides with a Connector
16.5. Shared State
16.6. RPC Calls Between Client- and Server-Side
16.7. Component and UI Extensions
16.8. Styling a Widget
16.9. Component Containers
16.10. Creating Add-ons
16.11. Migrating from Vaadin 6
16.12. Integrating JavaScript Components and Extensions
IV. Vaadin Add-ons
17. Using Vaadin Add-ons
17.1. Overview
17.2. Downloading Add-ons from Vaadin Directory
17.3. Installing Add-ons in Eclipse with Ivy
17.4. Using Add-ons in a Maven Project
17.5. Troubleshooting
18. Vaadin Charts
18.1. Overview
18.2. Installing Vaadin Charts
18.3. Basic Use
18.4. Chart Types
18.5. Chart Configuration
18.6. Chart Data
18.7. Advanced Uses
18.8. Timeline
19. Vaadin JPAContainer
19.1. Overview
19.2. Installing
19.3. Defining a Domain Model
19.4. Basic Use of JPAContainer
19.5. Entity Providers
19.6. Filtering JPAContainer
19.7. Querying with the Criteria API
19.8. Automatic Form Generation
19.9. Using JPAContainer with Hibernate
20. Mobile Applications with TouchKit
20.1. Overview
20.2. Considerations Regarding Mobile Browsing
20.3. Installing Vaadin TouchKit
20.4. Importing the Vornitologist Demo
20.5. Creating a New TouchKit Project
20.6. Elements of a TouchKit Application
20.7. Mobile User Interface Components
20.8. Advanced Mobile Features
20.9. Offline Mode
20.10. Building an Optimized Widget Set
20.11. Testing and Debugging on Mobile Devices
21. Vaadin TestBench
21.1. Overview
21.2. Installing Vaadin TestBench
21.3. Preparing an Application for Testing
21.4. Using Vaadin TestBench Recorder
21.5. Developing JUnit Tests
21.6. Taking and Comparing Screenshots
21.7. Running Tests in a Distributed Environment
21.8. Headless Testing
21.9. Known Issues
A. Songs of Vaadin
Index