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?
Related
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() };
}
}
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.
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?
I want to convert the selected date into the format"dd-MM-yyyy" because c.getTime returns "Sun Mar 3 12:34:46 IST 2013"
private class MyDateListener implements DateListener {
public void dateChanged(DateEvent e) {
Calendar c = e.getSelectedDate();
if (c != null) {
try {
SimpleDateFormat parser = new SimpleDateFormat(c.getTime().toString());
SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yyyy");
Date date;
date = parser.parse(date1);
output = formatter.format(date);
System.out.println(output);
} catch (ParseException ex) {
Logger.getLogger(Example1.class.getName()).log(Level.SEVERE, null, ex);
}
} else {
System.out.println("No time selected.");
}
}
}
Do you want:
SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy");
System.out.println(sdf.format(c.getTime());
The getTime() function actually returns a date, which you can pass to your formatter, so there is no need to parse it.
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