How to handle different date formats in Spring MVC controller? - java

Is it possible to handle different date format in a Spring MVC controller?
I know that setting something like this
#InitBinder
protected void initBinder(WebDataBinder binder) {
SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
binder.registerCustomEditor(Date.class, new CustomDateEditor(
dateFormat, false));
}
I can handle dd/MM/yyyy format, but what if i want to parse also dates in yyyyMMddhhmmss format? Should I add multiple CustomDateEditors in my controller?

If you need it only at puntual cases, you can register the custom editor attached to a field in the form:
DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy", this.getLocale(context));
DateFormat dateTimeFormat = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss SSS", this.getLocale(context));
binder.registerCustomEditor(Date.class, new CustomDateEditor(dateTimeFormat, true));
binder.registerCustomEditor(Date.class, "name.of.input", new CustomDateEditor(dateTimeFormat, true));

Inspired by Skipy
public class LenientDateParser extends PropertyEditorSupport {
private static final List<String> formats = new ArrayList<String>();
private String outputFormat;
static{
formats.add("dd-MM-yyyy HH:ss");
formats.add("dd/MM/yyyy HH:ss");
formats.add("dd-MM-yyyy");
formats.add("dd/MM/yyyy");
formats.add("dd MMM yyyy");
formats.add("MMM-yyyy HH:ss");
formats.add("MMM-yyyy");
formats.add("MMM yyyy");
}
public LenientDateParser(String outputFormat){
this.outputFormat = outputFormat;
}
#Override
public void setAsText(String text) throws IllegalArgumentException {
if(StringUtils.isEmpty(text))
return;
DateTime dt = null;
for(String format : formats){
try{
dt = DateTime.parse(text, DateTimeFormat.forPattern(format));
break;
}catch(Exception e){
if(log.isDebugEnabled())
log.debug(e,e);
}
}
if(dt != null)
setValue(dt.toDate());
}
#Override
public String getAsText() {
Date date = (Date) getValue();
if(date == null)
return "";
DateTimeFormatter f = DateTimeFormat.forPattern(outputFormat);
return f.print(date.getTime());
}
}

How about this. the above can go out of whack pretty soon.
public class MostLenientDateParser {
private final List<String> supportedFormats;
public MostLenientDateParser(List<String> supportedFormats) {
this.supportedFormats = supportedFormats;
}
public Date parse(String dateValue) {
for(String candidateFormat: supportedFormats) {
Date date = lenientParse(dateValue, candidateFormat);
if (date != null) {
return date;
}
}
throw new RuntimeException("tried so many formats, non matched");
}
private Date lenientParse(String dateCandidate, String dateFormat) {
try {
return new SimpleDateFormat(dateFormat).parse(dateCandidate);
} catch (Exception e) {
return null;
}
}
}
This could also be referenced through Spring Converters via a CustomDateEditor implementation for form-data binding.

For others having the same question, if you are using spring 3 You can use the awesome #DateTimeFormat(pattern="dd-MM-yyyy") in the field of your model.
Just make sure to register a conversionService with your org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter
You can have as much as you want of #DateTimeFormat in the same bean.

If at a time you receive only one format of date, then you could simply create one instance of DateFormat based on format
for example
Decide the format based on the input
DateFormat df = null;
if(recievedDate.indexOf("//")!=-1){
df = new SimpleDateFormat("dd/MM/yyyy")
}else{
df = new SimpleDateFormat("yyyyMMddhhmmss")
}

Not a great idea to have lenient date formatters when dealing with multiple locales. A date like 10/11/2013 will get parsed correctly with both dd/MM/YYYY and MM/dd/YYYY

Related

How to change the date format of Openxava date component?

We need to change the date format of the default openxava date(javaSript) component. default format is MM/dd/yy, and we need to change it to MM/dd/yyyy.
With the below link we can change the format of list view with implementing IFormatter interface. but in this conversation not clearly mention how to change the format of the date selection component.
https://sourceforge.net/p/openxava/discussion/419690/thread/40db1436/
Please help me to fix this issue...
To change the way a date, or any other type, is parsed and formatted you have to define a formatter for that type. To define a formatter edit the editors.xml file and add an entry like this:
<editor name="DateCalendar" url="dateCalendarEditor.jsp">
<formatter class="com.yourcompany.yourapp..formatters.YourDateFormatter" />
<for-type type="java.util.Date" />
</editor>
You have to write YourDateFormatter that implements IFormatter. For example, the default formatter for date is this:
package org.openxava.formatters;
import java.text.*;
import javax.servlet.http.*;
import org.openxava.util.*;
/**
* Date formatter with multilocale support. <p>
*
* Although it does some refinement in Spanish case, it support formatting
* on locale basis.<br>
*
* #author Javier Paniza
*/
public class DateFormatter implements IFormatter {
private static DateFormat extendedDateFormat = new SimpleDateFormat("dd/MM/yyyy"); // Only for some locales like "es" and "pl"
private static DateFormat [] extendedDateFormats = { // Only for some locales like "es", "fr", "ca" and "pl"
new SimpleDateFormat("dd/MM/yy"),
new SimpleDateFormat("ddMMyy"),
new SimpleDateFormat("dd.MM.yy")
};
public String format(HttpServletRequest request, Object date) {
if (date == null) return "";
if (Dates.getYear((java.util.Date)date) < 2) return "";
return getDateFormat().format(date);
}
public Object parse(HttpServletRequest request, String string) throws ParseException {
if (Is.emptyString(string)) return null;
if (isExtendedFormat()) {
if (string.indexOf('-') >= 0) { // SimpleDateFormat does not work well with -
string = Strings.change(string, "-", "/");
}
}
DateFormat [] dateFormats = getDateFormats();
for (int i=0; i<dateFormats.length; i++) {
try {
dateFormats[i].setLenient(false);
return dateFormats[i].parseObject(string);
}
catch (ParseException ex) {
}
}
throw new ParseException(XavaResources.getString("bad_date_format",string),-1);
}
private boolean isExtendedFormat() {
return "es".equals(Locales.getCurrent().getLanguage()) ||
"ca".equals(Locales.getCurrent().getLanguage()) ||
"pl".equals(Locales.getCurrent().getLanguage()) ||
"fr".equals(Locales.getCurrent().getLanguage());
}
private DateFormat getDateFormat() {
if (isExtendedFormat()) return extendedDateFormat;
return DateFormat.getDateInstance(DateFormat.SHORT, Locales.getCurrent());
}
private DateFormat[] getDateFormats() {
if (isExtendedFormat()) return extendedDateFormats;
return new DateFormat [] { getDateFormat() };
}
}

Unparsable date exception: string to java.sql.date

I have a problem with parsing a string to sql.date
This code works in my project only the first time, it will parse the date normally, but second time it throws exception.
I printed the date the function receives and it is the same format, for example 02.02.2016 was okey, I only changed month to 02.04.2016 and the exception was raised.
private final SimpleDateFormat dateFormat = new SimpleDateFormat("dd.mm.yyyy");
private final String sqldateFormat = "yyyy-mm-dd";
public java.sql.Date changeDate(String date) {
String newDate = "";
try {
java.util.Date d = dateFormat.parse(date);
dateFormat.applyPattern(sqldateFormat);
newDate = dateFormat.format(d);
} catch (ParseException e) {
e.printStackTrace();
}
return java.sql.Date.valueOf(newDate);
}
Try this
private final SimpleDateFormat dateFormat = new SimpleDateFormat("dd.mm.yyyy");
private final SimpleDateFormat sqldateFormat = new SimpleDateFormat("yyyy-mm-dd");
public java.sql.Date changeDate(String date) {
String newDate = "";
try {
java.util.Date d = dateFormat.parse(date);
newDate = sqldateFormat.format(d);
} catch (ParseException e) {
e.printStackTrace();
}
return java.sql.Date.valueOf(newDate);
}
Because during the fisrt execution you are modifying the pattern of the SimpleDateFormat it won't be able to parse the second date.
dateFormat.applyPattern(sqldateFormat); will modify the pattern to "yyyy-mm-dd" and then parsing 02.04.2016 will throw an exception.
this is because you change pattern of dateFormat.
This will work:
private final SimpleDateFormat dateFormat = new SimpleDateFormat("dd.mm.yyyy");
private final SimpleDateFormat sqlFormat = new SimpleDateFormat("yyyy-mm-dd");
public java.sql.Date changeDate(String date) {
String newDate = "";
try {
java.util.Date d = dateFormat.parse(date);
newDate = sqlFormat.format(d);
} catch (Exception e) {
e.printStackTrace();
}
return java.sql.Date.valueOf(newDate);
}
Apparently, this will work for the first run, but not for the second. Your problem is that you call applyPattern(), so it'll expect the new dates in sql date format only.
Here is a little better code:
private final SimpleDateFormat dateFormat = new SimpleDateFormat("dd.mm.yyyy");
private final SimpleDateFormat sqlFormat = new SimpleDateFormat("yyyy-mm-dd");
public java.sql.Date changeDate(String date) {
String newDate = "";
try {
java.util.Date d = dateFormat.parse(date);
newDate = sqlFormat.format(d);
} catch (ParseException e) {
e.printStackTrace();
}
return java.sql.Date.valueOf(newDate);
}
Don't use valueOf().
If you have a java.util.Date and want a java.sql.Date (or java.sql.Timestamp), use the Date(long date) constructor:
java.sql.Date sqlDate = new java.sql.Date(utilDate.getTime());
Also, don't catch exceptions and continue execution without handling it (printing it is not handling it).
Meaning that your code should be:
private final SimpleDateFormat dateFormat = new SimpleDateFormat("dd.mm.yyyy");
public java.sql.Date changeDate(String date) {
try {
return new java.sql.Date(dateFormat.parse(date).getTime());
} catch (ParseException e) {
throw new IllegalArgumentException("Invalid date: " + date);
}
}
Warning: SimpleDateFormat is not thread-safe:
Date formats are not synchronized. It is recommended to create separate format instances for each thread. If multiple threads access a format concurrently, it must be synchronized externally.

Formatting and validating a date in JSF

So I want to format my dateinputfield as "dd-MM-yyyy" and then validate that the date is not before tomorrow.
This is the relevant code in my view:
<h:inputText id="dueDate" required="true" value="#{submitRepairBean.dueDate}">
<f:convertDateTime pattern="dd-MM-yyyy"/>
<f:validator validatorId="be.kdg.repaircafe.validators.DueDateValidator"/>
</h:inputText>
This is my custom validator:
#FacesValidator("be.kdg.repaircafe.validators.DueDateValidator")
public class DueDateValidator implements Validator {
#Override
public void validate(FacesContext context, UIComponent component, Object value) throws ValidatorException {
System.out.println(value.toString()); //For some reason this prints Wed Jul 23 02:00:00 CEST 2014 when inputting 23-07-2014
DateTime date = new DateTime(value.toString());
long dueDateMillis = date.getMillis();
long oneDayMillis = 86400000;
Calendar tomorrowMidnight = new GregorianCalendar();
// reset hour, minutes, seconds and millis
tomorrowMidnight.set(Calendar.HOUR_OF_DAY, 0);
tomorrowMidnight.set(Calendar.MINUTE, 0);
tomorrowMidnight.set(Calendar.SECOND, 0);
tomorrowMidnight.set(Calendar.MILLISECOND, 0);
tomorrowMidnight.add(Calendar.DAY_OF_MONTH, 1);
if (dueDateMillis + oneDayMillis < tomorrowMidnight.getTimeInMillis()) {
throw new ValidatorException(new FacesMessage("You can not have something repaired before tomorrow!"));
}
}
Now the thing I don't understand is why it doesn't print in the converted format (dd-MM-yyyy), even then I don't care so much as long as I get the correct amount of milliseconds.
However, the DateTime constructor then throws an exception that the date is in an invalid format.
I've tried using SimpleDateFormat as well, with no luck.
The converter it will show you the date in this format on the page (in the jsp/html page). What it does, is converting the date in a string in the format dd-mm-yyyy. When you pass the calue in the validate function, it is not converted in the string in the format dd-MM-yyyy. it is a date, dueDate is a date, so by printing value.toString() is just converts the date value to a string. So the object is a date and just by casting to Date is should work. if you want in the code to print it in the format dd-MM-yyyy try this
Date date = (Date) value;
SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy");
String strDate = sdf.format(date);
System.out.println(strDate );
#FacesValidator("validator.dateValidator")
public class DateValidator implements Validator, ClientValidator {
final static String DATE_FORMAT = "dd-MM-yyyy";
public DateValidator() {
}
public void validate(FacesContext context, UIComponent component, Object value) throws ValidatorException {
if (value == null || StringUtils.isEmpty((String) value.toString())) {
return;
}
SimpleDateFormat objDf = new SimpleDateFormat(DATE_FORMAT);
objDf.setLenient(false);
try {
try {
Date data = new Date();
data.setDate(data.getDate() + 1);
if(objDf.parse(value.toString()).before(data)){
((UIInput) component).setValid(false);
throw new ValidatorException(new FacesMessage("You can not have something repaired before tomorrow!"));
}
} catch (ParseException e) {
((UIInput) component).setValid(false);
throw new ValidatorException(new FacesMessage(MessageUtils.ALERTA, "Data informada não Válida!", ""));
}
} catch (ParseException e) {
throw new ValidatorException(new FacesMessage("Invalid Date!"));
}
}
public Map<String, Object> getMetadata() {
return null;
}
public String getValidatorId() {
return "validator.dateValidator";
}
}

why this happen in type conversion?

i am new to springMVC ,today i write a DateConverter
like this
public class DateConverter implements Converter<String,Date>{
private String formatStr = "";
public DateConverter(String fomatStr) {
this.formatStr = formatStr;
}
public Date convert(String source) {
SimpleDateFormat sdf = null;
Date date = null;
try {
sdf = new SimpleDateFormat(formatStr);
date = sdf.parse(source);
} catch (ParseException e) {
e.printStackTrace();
}
return date;
}
}
then i write a controller like this
#RequestMapping(value="/converterTest")
public void testConverter(Date date){
System.out.println(date);
}
congfigure it to applicationContext,i am sure the DateConverter has been initialized correctly,when i test my converter with
http://localhost:8080/petStore/converterTest?date=2011-02-22
the browser says:
HTTP Status 400 -
type Status report
message
description The request sent by the client was syntactically incorrect ().
somebody could help me with it? thanks in advance
You have a typo in your converter. You misspelled the constructor param, so the assignment has no effect. Instead of:
public DateConverter(String fomatStr) {
this.formatStr = formatStr;
}
try:
public DateConverter(String formatStr) {
this.formatStr = formatStr;
}
There may be other issues, but at a minimum you'll want to fix that. I'm assuming you are using yyyy-MM-dd for your date format?

Spring Java #DateTimeFormat

I have created a helper to parse time froma webservice and output inanother format
using #DateTimeFormat. However in my jsp view this is not formatted. Am I using this wrong?
#Component
public class DateParserHelper {
#DateTimeFormat(style="F-")
public Date getFormattedDate() {
return formattedDate;
}
public void setFormattedDate(Date formattedDate) {
this.formattedDate = formattedDate;
}
public Date formattedDate;
public void setDate(String date) throws ParseException {
DateFormatter dateFormatter = new DateFormatter("y-M-d");
setFormattedDate( dateFormatter.parse(date, UK));
}
}
If you are using JSTL in your jsp, you could use formatDate to format your date :
<fmt:formatDate value="${yourDate}" pattern="dd/MM/yyyy" />
Try SimpleDateFormat
String pattern = "MM/dd/yyyy";
...
public void setDate(String date) {
SimpleDateFormat format = new SimpleDateFormat(pattern);
setFormattedDate(format.parse(date));
}

Categories