Vaadin : Use a custom converter on grid

Here a simple Vaadin converter to format dateTime in GRID.
ConvertToModel method is not implemented because converter is not associated to any field.

How to use Grid

  CustomFormatDateStringConverter dateConverter = new CustomFormatDateStringConverter();
  grid.getColumn("beanDateAttr").setConverter(dateConverter);

Converter Implementation

package com.common.utils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

import com.vaadin.data.util.converter.Converter;

public class CustomFormatDateStringConverter implements Converter<String, String> {
	SimpleDateFormat dateParser = new SimpleDateFormat("ddMMyyyy");
	SimpleDateFormat dateFormatter = new SimpleDateFormat("dd/MM/yyyy");

	@Override
	public String convertToModel(String value,
			Class<? extends String> targetType, Locale locale)
			throws com.vaadin.data.util.converter.Converter.ConversionException {
			
			// If using in a grid this part can be omitted
			
			return value;
	}

	@Override
	public String convertToPresentation(String value,
			Class<? extends String> targetType, Locale locale)
			throws com.vaadin.data.util.converter.Converter.ConversionException {
			
			if (value!=null && !value.isEmpty()) {
				try {
					Date date = dateParser.parse(value);
					value = dateFormatter.format(date);
				} catch (ParseException e) {
					e.printStackTrace();

				}
			}else{
				value="";
			}
			return value;
	}

	@Override
	public Class<String> getModelType() {
		return String.class;
	}

	@Override
	public Class<String> getPresentationType() {
		return String.class;
	}

}

Leave a Reply

Your email address will not be published.

Antispam Question * Time limit is exhausted. Please reload CAPTCHA.

This site uses Akismet to reduce spam. Learn how your comment data is processed.