How to change the date format of Openxava date component? - java

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() };
}
}

Related

How to change GMT to PST format in Java?

I have a code that displays time in GMT and I need to show it in PST. How can I modify the below code to get the time in PST?
Code
public static final String FORMAT = "MM/dd/yyyy";
public static final String OUTPUT_FORMAT_STD_DATE6 = "MM/dd/yy hh:mm a";
public static final String INPUT_FORMAT_STD_TIMESTAMP = "yyyy-MM-dd HH:mm:ss";
public static String formatDate(String strDate, String inputFormat, String outputFormat) {
Date date = convertStringToDate(strDate,inputFormat);
String displayDateString = formatDate(date, outputFormat);
return displayDateString;
}
formatDate is being called here
public void endElement(String uri, String localName, String qName) throws SAXException {
if( EVENT.equalsIgnoreCase( qName ) ) {
auditEntries.add(entry);
} else if( LOG_TIME.equalsIgnoreCase( qName ) ) {
String time = content.toString();
entry.setLogTime( DateUtils.formatDate(time, "yyyy-MM-dd'T'HH:mm:ss", DateUtils.OUTPUT_FORMAT_STD_DATE6));
}
Please help, I am new b in writing Java code.
This is how I am doing it.
public static String formatDate(String strDate, String inputFormat, String outputFormat) {
Date date = convertStringToDate(strDate,inputFormat);
DateFormat pstFormat = new SimpleDateFormat( outputFormat );
pstFormat.setTimeZone( TimeZone.getDefault() );
String displayDateString = formatDate(date, outputFormat);
return displayDateString;
}
Thanks
Once you have a Date object you can convert it to a timezoned string using SimpleDateFormat. Below is a simple example.
Using 3 letter timezone IDs has been deprecated, so you should use GMT+-hour:minute format, or region specific string like America/Los_Angeles as suggested by #VGR
For compatibility with JDK 1.1.x, some other three-letter time zone IDs (such as "PST", "CTT", "AST") are also supported. However, their use is deprecated because the same abbreviation is often used for multiple time zones (for example, "CST" could be U.S. "Central Standard Time" and "China Standard Time"), and the Java platform can then only recognize one of them.
Ref:https://docs.oracle.com/javase/7/docs/api/java/util/TimeZone.html
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;
public class DateTest {
public static final String OUTPUT_FORMAT_STD_DATE6 = "MM/dd/yy hh:mm a";
public static void main(String[] args) {
Date date = new Date();
String gmtDateStr = dateToTimzoneString(date, "GMT", OUTPUT_FORMAT_STD_DATE6);
System.out.println(gmtDateStr);
//3 Letter String usage is deprecated
String pstDateStr = dateToTimzoneString(date, "PST", OUTPUT_FORMAT_STD_DATE6);
System.out.println(pstDateStr);
//Correct way
pstDateStr = dateToTimzoneString(date, "GMT+5", OUTPUT_FORMAT_STD_DATE6);
System.out.println(pstDateStr);
}
public static String dateToTimzoneString(Date date, String timeZoneStr, String outputFormat){
SimpleDateFormat sd = new SimpleDateFormat(outputFormat);
sd.setTimeZone(TimeZone.getTimeZone(timeZoneStr));
return sd.format(date);
}
}
This is how I did it.
public static String convertUTC( String strDate, String inputFormat, String outputFormat ) {
String displayDateString = null;
try {
DateFormat inFormat = new SimpleDateFormat( inputFormat );
inFormat.setTimeZone( TimeZone.getTimeZone( "UTC" ) );
Date date = inFormat.parse( strDate );
DateFormat outFormat = new SimpleDateFormat( outputFormat );
outFormat.setTimeZone( TimeZone.getDefault() );
displayDateString = formatDate(date, outputFormat);
} catch ( ParseException pe ) {
pe.printStackTrace();
}
return displayDateString;
}

How to set locale in Blackberry Java(change date to Spanish language)

How to set Spanish locale in blackberry below is my code and its giving error,
I am using net.rim.device.api.i18n.Locale library
import net.rim.device.api.i18n.Locale;
import net.rim.device.api.i18n.SimpleDateFormat;
public static String formatDate(Date date)
{
String dateFormat = UserSettingManager.getUserSetting(UserSettingManager.PREF_DATE_FORMAT);
if(StringUtils.isEmptyOrWhitespace(dateFormat))
{
dateFormat = DEFAULT_DATE_FORMAT;
}
SimpleDateFormat formatter;
try
{
if(!isLanguageChangeToSpanish()){
formatter = new SimpleDateFormat(dateFormat);
}else {
formatter = new SimpleDateFormat(dateFormat, Locale.get(Locale.LOCALE_es, "es"));
}
}
catch(Exception e)
{
//If format received from server is wrong just display the default...
if(!isLanguageChangeToSpanish()){
formatter = new SimpleDateFormat(DEFAULT_DATE_FORMAT);
}else {
formatter = new SimpleDateFormat(DEFAULT_DATE_FORMAT, Locale.get(Locale.LOCALE_es, "es"));
}
}
return formatter.format(date);
}
ERROR : cannot find symbol constructor SimpleDateFormat(java.lang.String,net.rim.device.api.i18n.Locale)
Looks like a compiler problem.
That constructor exists since OS 4.5. Maybe you have the compiler set up to an older OS version?

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?

How to handle different date formats in Spring MVC controller?

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

Categories