Date and Time with Joda Time

Joda Time is a fantastic Date and Time API. VRaptor comes with four converters for Joda Time base classes, common used by web applications:

  1. org.joda.time.LocalDate as an immutable Date class (not DateTime, only Date).
  2. org.joda.time.LocalTime as an immutable Time class.
  3. org.joda.time.YearMonthDay the old immutable Date class. You should use LocalDate instead. It is now deprecated.
  4. org.joda.time.TimeOfDay the old immutable Time class. You should use LocalTime instead. It is now deprecated.

The converters are also based on the user Locale as LocaleCalendarDateConverter and LocaleCalendarTimeConverter are.

The input String for both Date and Time must be always in DateFormat.SHORT format. E.g: MM/dd/yyy and hh:mm for Locale.ENGLISH.

Using the Converters

Just enable what you want in vraptor.xml:

<vraptor>
        <converter>org.vraptor.converter.joda.LocalDateConverter</converter>
        <converter>org.vraptor.converter.joda.LocalTimeConverter</converter>

        <!-- The old ones are now deprecated! -->
        <converter>org.vraptor.converter.joda.YearMonthDayConverter</converter>
        <converter>org.vraptor.converter.joda.TimeOfDayConverter</converter>
</vraptor>

I need a date!

If a date-only object (not timestamp) is needed, we can simply use the method parameter to read the request parameter value.

package org.vraptor.example.joda.time;

import org.joda.time.LocalDate;
import org.vraptor.annotations.Component;
import org.vraptor.annotations.Parameter;

@Component("myComponent")
public class MyComponent {

        private LocalDate date;

        public void method(LocalDate date) {
                System.out.println("Date: " + date);
                this.date = date;
        }
        
        public LocalDate getDate() {
                return this.date;
        }
}

Done! Simply call http://domain.com/context/myComponent.method.logic?date=1/1/1970 and the date field will be automatically filled!

I need a time!

When a time object is needed, we can also read it with the method parameter and the converter will do the job.

package org.vraptor.example.joda.time;

import org.joda.time.LocalTime;
import org.vraptor.annotations.Component;
import org.vraptor.annotations.Parameter;

@Component("myComponent")
public class MyComponent {

        private LocalTime time;
        
        public void method(LocalTime time) {
                System.out.println("Time: " + time);
                this.time = time;
        }
        
        public LocalTime getTime() {
                return this.time;
        }
}

Done again! Simply call http://domain.com/context/myComponent.method.logic?time=11:30 and the time field will be automatically filled!