Date Format not working in service class of spring? - java

public class DateCreation {
public static void main(String[] args) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date date = new Date();
String format = sdf.format(date);
System.out.print("date is:"+format);
}
}
This is working fine and output is: date is:2014-02-11
But when I use same syntax in Service layer of spring MVC than it results as:
date is:????-??-??
Here is code in spring. There is an #Override function in which I have used it.
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date date = new Date();
String format = sdf.format(date);
logger.info("current date is:"+format);
What could be the error?

#InitBinder
public void initBinder(WebDataBinder webDataBinder) {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
dateFormat.setLenient(false);
webDataBinder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
}

Related

Getting Blank Date as string from a custom date method

I am making a date filter for which I have created a custom method for date to be parse in specific date format.
I have date with to two formats dd MMM yyyy & yyyy-mm-dd which is passed in a single method to be parse and return in format of yyyy-mm-dd. As I have a complex structure at end both type of formatted string will go under the date parsing method.
ISSUE:: I am getting a blank string as return from this method when format is in yyyy-mm-dd. please provide me inputs of where i am wrong. Below is the code
//fetching date from methods
String current_date=CurrentFilterPeriod.dateParsing("2017-04-02");
String prev_date=CurrentFilterPeriod.dateParsing("01 Apr 2017");
//singleton file for date filter method
public class CurrentFilterPeriod {
private static Calendar cal = getInstance();
private static Date current_date = cal.getTime();
//defined formats for date
private static SimpleDateFormat formatter = new SimpleDateFormat("dd MMM yyyy");
private static SimpleDateFormat formatterString = new SimpleDateFormat("yyyy-MM-dd");
//method for parsing date
public static String dateParsing(String date){
Date newDate;
String returnDate = "";
if (date.equals(formatter.toPattern())){
returnDate=date;
}
Log.e("DB","date===>"+date);
try {
newDate = formatter.parse(date);
Log.e("DB","New Date===>"+newDate);
returnDate=formatterString.format(newDate);
Log.e("DB","returnDate===>"+returnDate);
} catch (ParseException e) {
e.printStackTrace();
}
return returnDate;
}
}
RESULT:: current_date="" prev_date="2017-04-01"
I am stuck here please help me or tell me other methods to get by desired output.Want result in format of yyyy-mm-dd
As you want result format like: yyyy-mm-dd. You need to check your Date String with formatterString formatter.
Change your code with:
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
boolean isValidDate(String input) {
try {
format.parse(input);
return true;
}
catch(ParseException e){
return false;
}
}
Now call the method using:
//method for parsing date
public static String dateParsing(String date) {
Date newDate;
String returnDate = "";
if (isValidDate(date)) {
returnDate = date;
return returnDate;
} else {
Log.e("DB", "date===>" + date);
try {
newDate = formatter.parse(date);
Log.e("DB", "New Date===>" + newDate);
returnDate = formatterString.format(newDate);
Log.e("DB", "returnDate===>" + returnDate);
} catch (ParseException e) {
e.printStackTrace();
}
}
return returnDate;
}

Caldroid calendar unparsable date exception

I am trying to get the selected date in dd/MM/yyyy format from Caldroid calendar but when I am parsing the date it will throw an following error.
java.text.ParseException: Unparseable date: "Thu May 04 00:00:00 GMT 2017" (at offset 0)
Below is my code:-
final SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
final CaldroidListener caldroidListener = new CaldroidListener() {
#Override
public void onSelectDate(Date date, View view) {
try {
String dateParse = date.toString();
Log.d("Date before parse: ",date.toString());
sdf.parse(dateParse);
Log.d("Date after parse: ",dateParse);
eventDate.setText(dateParse);
}catch(ParseException e){
e.printStackTrace();
}
}
};
This does what you want your code to do (without the logging):
final SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
final CaldroidListener caldroidListener = new CaldroidListener() {
#Override
public void onSelectDate(Date date, View view) {
eventDate.setText(sdf.format(date));
}
};
You use SimpleDateFormat#format to get a formatted string out of your Date.

Unable to view the date and time in Motox

I am developing an app in which i want to display the date and time the code works fine in other devices except in motox.I don't know where the problem is.
public static String convertDateTimeForm(Context context,String date){
String date_tim=date;
//date_tim=date.toString().replaceAll("\\.","");
//date_tim=date_tim.replaceAll("AM","am").replaceAll("PM","pm");
String newTime="";
try{
SimpleDateFormat dateFormat=null;
dateFormat= new SimpleDateFormat("yyyy-MMM-dd hh:mm a");
simpleDateFormat convertFormat;
convertFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date newDate=null;
newDate=dateFormat.parse(date_tim);
newTime=convertFormat.format(newDate);
}catch(Exception e){
e.printStackTrace();
}
return newTime;
}

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.

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