I use Spring Boot and I try to save some date in MongoDB. My input date is
"2017-08-14T12:59"
I get this error while saving:
Failed to read HTTP message: org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error: Failed to parse Date value '2017-08-14T12:59': Can not parse date "2017-08-14T12:59.000Z": while it seems to fit format 'yyyy-MM-dd'T'HH:mm:ss.SSS'Z'', parsing fails (leniency? null); nested exception is com.fasterxml.jackson.databind.JsonMappingException: Failed to parse Date value '2017-08-14T12:59': Can not parse date "2017-08-14T12:59.000Z": while it seems to fit format 'yyyy-MM-dd'T'HH:mm:ss.SSS'Z'', parsing fails (leniency? null) (through reference chain:
In my POJO i tried like this:
#JsonDeserialize(using= CustomDateDeserialize.class)
private Date inputDateTime;
and I've implemented Deserializer like this :
private SimpleDateFormat dateFormat = new SimpleDateFormat(
"yyyy-MM-dd HH:mm");
#Override
public Date deserialize(JsonParser paramJsonParser,
DeserializationContext paramDeserializationContext)
throws IOException, JsonProcessingException {
String str = paramJsonParser.getText().trim();
try {
return dateFormat.parse(str);
} catch (ParseException e) {
}
return paramDeserializationContext.parseDate(str);
}
What else I miss here? Any help appreciated.
you need to modify format in your deserializer.
SimpleDateFormat dateFormat = new SimpleDateFormat(
"yyyy-MM-dd'T'HH:mm");
any way simpledatetimeformat is not thread safe. if you java8 use DateTimeFormat.
Why don't you try Instant library
#Field("your_db_id_name")
private Instant inputDateTime;
public void setInputDateTime(Instant inputDateTime) {
this.inputDateTime = inputDateTime;
}
public void getInputDateTime() {
return inputDateTime;
}
You can set Filed by using Instant.now()
Related
In My project Dashboard we fetch data using elasticsearch, I send parallel requests for different section of dashboard. Now strange behaviour has started coming. Out of this bunch of request I send almost 1-2 requests always fails. If I reload the page then chances are that the same request will fail or some other.
Error is always this
Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.springframework.data.elasticsearch.ElasticsearchException: failed to map source
Stacktrace always starts with below.
java.lang.NumberFormatException: For input string: ""
at java.base/java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
Anyone could figure out by looking at this at error is coming when formatting date attribute when reading via elastic.
Below is how attribute looks in dto.
#Field(type = FieldType.Date, format = DateFormat.date, pattern = "uuuu-MM-dd HH:mm:ss")
#JsonDeserialize(using = CustomDateDeserializer.class)
private Date lastUpdateDate;
This is CustomDateDeserializer class,
public class CustomDateDeserializer extends StdDeserializer<Date> {
private SimpleDateFormat formatter = new SimpleDateFormat("uuuu-MM-dd HH:mm:ss");
public CustomDateDeserializer() {
this(null);
}
public CustomDateDeserializer(Class<?> vc) {
super(vc);
}
#Override
public Date deserialize(JsonParser jsonparser, DeserializationContext ctxt) throws IOException, JsonProcessingException {
String date = jsonparser.getText();
try {
return formatter.parse(date);
} catch (ParseException e) {
throw new RuntimeException(e);
}
}
}
Issue is failing request has no logical behaviour, because of which I am not able to figure out the cause.
Any input on this ?
I have a bean class where I am setting the recReceived time using the below code. When I am executing the below code, I am getting error
Exception in thread "main" java.lang.IllegalArgumentException: Cannot
deserialize value of type java.sql.Timestamp from String
............
public static void main(String[] args) {
TestBean TestBean = new TestBean();
TestBean.setRecReceived(new Timestamp(System.currentTimeMillis()));
Gson gson = new Gson();
String jsonData = gson.toJson(TestBean); // Cannot ignore this part as it is sent from first server to second server
Map<String, Object> map = new ObjectMapper().readValue(jsonData, HashMap.class); //Received at server end
TestBean abc = (TestBean) convertMapToEntity(map, TestBean.class);
}
// Cannot edit this function
public static Object convertMapToEntity(Map<String, Object> object, Class<?> objClass) {
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
return objectMapper.convertValue(object, objClass);
}
// Bean class - Cannot edit this file
import java.sql.Timestamp;
public class TestBean {
Timestamp recReceived;
Timestamp responseSent;
// getter and setter
}
It will be really helpful if someone can help me let know what I am doing wrong in the code or can any change be done in code without touching the non editable function or file
Thanks in advance
You are seeing this exception :
java.lang.IllegalArgumentException: Cannot deserialize value of type
java.sql.Timestamp from String "Jun 15, 2022, 07:54:56 PM": not a
valid representation (error: Failed to parse Date value 'Jun 15, 2022,
07:54:56 PM': Cannot parse date "Jun 14, 2022, Jun 15, 2022, 07:54:56
PM": not compatible with any of standard forms
("yyyy-MM-dd'T'HH:mm:ss.SSSX", "yyyy-MM-dd'T'HH:mm:ss.SSS", "EEE, dd
MMM yyyy HH:mm:ss zzz", "yyyy-MM-dd"))
beacause your JSON is having the date format which is not compatible with standard date format that Jackson uses for deserializations.
Below are standard formats for a date which Jackson supports:
yyyy-MM-dd’T’HH:mm:ss.SSSZ
yyyy-MM-dd’T’HH:mm:ss.SSS
EEE, dd MMM yyyy HH:mm:ss zzz
yyyy-MM-dd
To fix this, you will use
.setDateFormat() method which configures Gson to serialize Date objects according to the pattern provided.
You will need to set one of above mentioned patterns which jackson support.
Here is the complete code:
public static void main(String[] args) throws JsonProcessingException {
TestBean TestBean = new TestBean();
TestBean.setRecReceived(new Timestamp(System.currentTimeMillis()));
GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.setDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS");
Gson gson = gsonBuilder.create();
String jsonData = gson.toJson(TestBean); // Cannot ignore this part as it is sent from first server to second server
Map<String, Object> map = new ObjectMapper().readValue(jsonData, HashMap.class); //Received at server end
TestBean abc = (TestBean) convertMapToEntity(map, com.example.demo.dto.TestBean.class);
System.out.println(abc);
}
If you run above code, you should see output like this:
TestBean{recReceived=2022-06-14 04:01:56.279, responseSent=null}
I am implementing an application that gets the data from certin endponts in json formats and tries to deserialize tem to Java Objects but I have problems with the parsing of the date in the JSON.This is how the Date looks like in the JSON: "/Date(1633122000000+0300)/" and I cannot find information in Google how to successfully parse this format.
{
"Date": "/Date(1633122000000+0300)/",
"Filled": 0,
"Needed": 0,
"Paid": 0
}
This is the pojo I use to deserialize the data to using Jackson ObjectMapper:
import java.util.Date;
#Data
#AllArgsConstructor
#NoArgsConstructor
public class TimeByDateSheet {
#JsonProperty("Date")
#JsonFormat(timezone = "GMT+03:00")
#JsonDeserialize(using = DateDeserializer.class, as=Date.class)
private Date date;
#JsonProperty("Filled")
private Long filled;
#JsonProperty("Needed")
private Long needed;
#JsonProperty("Paid")
private Integer paid;
}
And here is my DateDeserializer:
#SuppressWarnings("serial")
public class DateDeserializer extends JsonDeserializer<Date> {
#Override
public Date deserialize(JsonParser jsonParser, DeserializationContext context)
throws IOException, JsonProcessingException {
SimpleDateFormat simpleDateFormat =
new SimpleDateFormat("yyyy-MM-dd HH:mm:ss zzz", Locale.getDefault());
String dateStr = jsonParser.getText();
Date date;
try{
date = simpleDateFormat.parse(dateStr);
}catch(ParseException e){
throw new RuntimeException(e);
}
return date;
}
}
But it does not work correctly. I get the following exception:
Connected to the target VM, address: '127.0.0.1:52760', transport: 'socket'
SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder".
SLF4J: Defaulting to no-operation (NOP) logger implementation
SLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further details.
Exception in thread "main" com.fasterxml.jackson.databind.JsonMappingException: java.text.ParseException: Unparseable date: "/Date(1633035600000+0300)/" (through reference chain: java.util.ArrayList[0]->com.dataart.forecasts.pojo.timebydate.TimeByDateSheet["Date"])
at com.fasterxml.jackson.databind.JsonMappingException.wrapWithPath(JsonMappingException.java:392)
at com.fasterxml.jackson.databind.JsonMappingException.wrapWithPath(JsonMappingException.java:351)
at com.fasterxml.jackson.databind.deser.BeanDeserializerBase.wrapAndThrow(BeanDeserializerBase.java:1821)
at com.fasterxml.jackson.databind.deser.BeanDeserializer.vanillaDeserialize(BeanDeserializer.java:315)
at com.fasterxml.jackson.databind.deser.BeanDeserializer.deserialize(BeanDeserializer.java:176)
at com.fasterxml.jackson.databind.deser.std.CollectionDeserializer._deserializeFromArray(CollectionDeserializer.java:355)
at com.fasterxml.jackson.databind.deser.std.CollectionDeserializer.deserialize(CollectionDeserializer.java:244)
at com.fasterxml.jackson.databind.deser.std.CollectionDeserializer.deserialize(CollectionDeserializer.java:28)
at com.fasterxml.jackson.databind.deser.DefaultDeserializationContext.readRootValue(DefaultDeserializationContext.java:322)
at com.fasterxml.jackson.databind.ObjectMapper._readMapAndClose(ObjectMapper.java:4675)
at com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:3630)
at com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:3613)
at com.dataart.forecasts.DataProcessor.deserializeTimeByDateSheetsList(DataProcessor.java:198)
at com.dataart.forecasts.ForecastReportApplication.main(ForecastReportApplication.java:50)
Caused by: java.lang.RuntimeException: java.text.ParseException: Unparseable date: "/Date(1633035600000+0300)/"
at com.dataart.forecasts.DateDeserializer.deserialize(DateDeserializer.java:28)
at com.dataart.forecasts.DateDeserializer.deserialize(DateDeserializer.java:16)
at com.fasterxml.jackson.databind.deser.impl.MethodProperty.deserializeAndSet(MethodProperty.java:129)
at com.fasterxml.jackson.databind.deser.BeanDeserializer.vanillaDeserialize(BeanDeserializer.java:313)
... 10 more
Caused by: java.text.ParseException: Unparseable date: "/Date(1633035600000+0300)/"
at java.base/java.text.DateFormat.parse(DateFormat.java:395)
at com.dataart.forecasts.DateDeserializer.deserialize(DateDeserializer.java:26)
... 13 more
Could someone help me, please. I searched a lot in internet but could not find a solution.
Thank you in advance! :)
It looks like there is a problem generating the JSON. I really don't think you want to have the dates formatted like that. Right now, you have some odd text surrounding a unix timestamp in milliseconds followed by a zone offset. You are also using the old and rather frowned-upon Date and SimpleDateFormat classes rather than the newer java.time API. However, it is possible to deserialize your date format. Here is one way:
public class DateDeserializer extends JsonDeserializer<Date> {
#Override
public Date deserialize(JsonParser jsonParser, DeserializationContext context)
throws IOException, JsonProcessingException {
Pattern pattern = Pattern.compile("/Date\\((\\d+)([+-]\\d+)\\)/");
Matcher matcher = pattern.matcher(jsonParser.getText());
if (matcher.find()) {
String timestamp = matcher.group(1);
String offset = matcher.group(2);
Instant instant = Instant.ofEpochMilli(Long.parseLong(timestamp));
ZonedDateTime zdt = instant.atZone(ZoneId.of(offset));
instant = zdt.toInstant();
return Date.from(instant);
} else {
throw new RuntimeException("Invalid format: " + jsonParser.getText());
}
}
}
java.time
For this answer I am assuming:
The time in your JSON may come with or without the UTC offset.
You can go all-in on java.time, the modern Java date and time API, and declare your variable to be of type Instant or OffsetDateTime, for example (not Date).
For JSON that comes with an offset such as +0300 declare your variable an OffsetDateTime. Then use the following deserializer.
public class OdtDeserializer extends JsonDeserializer<OffsetDateTime> {
private static final DateTimeFormatter JSON_DATE_FORMATTER = new DateTimeFormatterBuilder()
.appendLiteral("/Date(")
.appendValue(ChronoField.INSTANT_SECONDS)
.appendValue(ChronoField.MILLI_OF_SECOND, 3)
.appendOffset("+HHMM", "Z")
.appendLiteral(")/")
.toFormatter();
#Override
public OffsetDateTime deserialize(JsonParser jsonParser, DeserializationContext context)
throws IOException {
String dateStr = jsonParser.getText();
return OffsetDateTime.parse(dateStr, JSON_DATE_FORMATTER);
}
}
For JSON that comes without offset like /Date(1636510000000)/ declare your variable Instant. Use a similar deserializer. Leave out the offset from the formatter. Parse into an Instant — the syntax is a bit different.
public class InstantDeserializerWIthoutOffset extends JsonDeserializer<Instant> {
private static final DateTimeFormatter JSON_DATE_FORMATTER = new DateTimeFormatterBuilder()
.appendLiteral("/Date(")
.appendValue(ChronoField.INSTANT_SECONDS)
.appendValue(ChronoField.MILLI_OF_SECOND, 3)
.appendLiteral(")/")
.toFormatter();
#Override
public Instant deserialize(JsonParser jsonParser, DeserializationContext context)
throws IOException {
String dateStr = jsonParser.getText();
return JSON_DATE_FORMATTER.parse(dateStr, Instant::from);
}
}
For JSON that may come with or without the offset still use Instant and just modify the formatter of the latter deserializer to include an optional offset:
private static final DateTimeFormatter JSON_DATE_FORMATTER = new DateTimeFormatterBuilder()
.appendLiteral("/Date(")
.appendValue(ChronoField.INSTANT_SECONDS)
.appendValue(ChronoField.MILLI_OF_SECOND, 3)
.optionalStart()
.appendOffset("+HHMM", "Z")
.optionalEnd()
.appendLiteral(")/")
.toFormatter();
If you cannot modify your POJO class and need to stay with Date, modify my Instant deserializer into a Date deserializer by changing the declaration and returning a Date like this:
String dateStr = jsonParser.getText();
Instant inst = JSON_DATE_FORMATTER.parse(dateStr, Instant::from);
return Date.from(inst);
Final solution catching both: /Date(1633035600000+0300)/ and /Date(-62135596800000)/ (the latter was also present at one place in oneof the JSONs). Thank you #DavidConrad
#Override
public Date deserialize(JsonParser jsonParser, DeserializationContext context) throws IOException, JsonProcessingException {
String dateString = jsonParser.getText();
Pattern pattern = Pattern.compile("/Date\\((-)?(\\d+)([+-]\\d+)?\\)/");
Matcher matcher = pattern.matcher(dateString);
if (!matcher.find()) {
throw new RuntimeException("Invalid format: " + dateString);
}
String timestamp = matcher.group(2);
String offset = matcher.group(3);
Instant instant = Instant.ofEpochMilli(Long.parseLong(timestamp));
if (nonNull(offset)) {
ZonedDateTime zdt = instant.atZone(ZoneId.of(offset));
instant = zdt.toInstant();
}
return Date.from(instant);
}
#DavidConrad Thank you, I will try your solution.
By the way, for now I made a workaround that works for me for now:
#Override
public Date deserialize(JsonParser jsonParser, DeserializationContext context) throws IOException, JsonProcessingException {
SimpleDateFormat dateFormattter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String dateStr = jsonParser.getText();
String timeZone = dateStr.substring(dateStr.indexOf("+") + 1, dateStr.indexOf(")"));
String timeZoneShift = String.format("%s:%s",
timeZone.substring(0, timeZone.length()/2),
timeZone.substring(timeZone.length()/2));
dateFormattter.setTimeZone(TimeZone.getTimeZone(String.format("GMT+%s", timeZoneShift)));
Long millis = 0L;
if (dateStr.contains("+") && !dateStr.contains("-")) {
millis = Long.parseLong(dateStr.substring(dateStr.indexOf("(") + 1, dateStr.indexOf("+")));
} else if (dateStr.contains("+") && !dateStr.contains("-")) {
millis = Long.parseLong(dateStr.substring(dateStr.indexOf("(") + 1, dateStr.indexOf(")")));
}
Date date = new Date(millis);
String stringDate= dateFormattter.format(date);
try {
date = dateFormattter.parse(stringDate);
} catch (ParseException e) {
throw new RuntimeException(e);
}
return date;
}
I'm working with Android Studio (java) to make the front part of my application, and I work with Spring Boot to the back part.
The SQL database uses TimeStamp.
So my problem is that when I send an object from front (Android) to back (Spring) throws an error:
Resolved [org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error: Cannot deserialize value of type java.util.Date from String "Feb 18, 2021 2:47:40 AM": not a valid representation (error: Failed to parse Date value 'Feb 18, 2021 2:47:40 AM': Cannot parse date "Feb 18, 2021 2:47:40 AM": not compatible with any of standard forms ("yyyy-MM-dd'T'HH:mm:ss.SSSX", "yyyy-MM-dd'T'HH:mm:ss.SSS", "EEE, dd MMM yyyy HH:mm:ss zzz", "yyyy-MM-dd")); nested exception is com.fasterxml.jackson.databind.exc.InvalidFormatException: Cannot deserialize value of type java.util.Date from String "Feb 18, 2021 2:47:40 AM": not a valid representation (error: Failed to parse Date value 'Feb 18, 2021 2:47:40 AM': Cannot parse date "Feb 18, 2021 2:47:40 AM": not compatible with any of standard forms ("yyyy-MM-dd'T'HH:mm:ss.SSSX", "yyyy-MM-dd'T'HH:mm:ss.SSS", "EEE, dd MMM yyyy HH:mm:ss zzz", "yyyy-MM-dd"))
at [Source: (PushbackInputStream); line: 1, column: 123] (through reference chain: com.prueba.dataproviders.model.Solicitud["fecha"])]
So I guess the problem its from Android sending information to Spring, but I don't know how to handle it...
MORE INFORMATION:
This is an example when I send information from Spring to Android:
{
"id": 23,
"fecha": "2021-02-18T02:47:40.000+00:00",
"estadoSolicitud": 1
}
I keep the attribute "fecha" which its a date in a Date variable.
But when I send the same object to back it sends:
{"estadoSolicitud":0,"fecha":"Feb 18, 2021 2:47:40 AM","id":23}
Thank you in advance <3
CODE:
At Spring Solicitud class:
#Entity
#Table(name = "solicitud")
public class Solicitud implements Serializable{
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
#GenericGenerator(name = "increment", strategy = "increment")
#Column(name = "id")
private int id;
#Column(name = "fecha", insertable = false)
private Date fecha;
#Column(name="estadoSolicitud")
private int estadoSolicitud; // "0 Pendiente, 1 Realizada 2 Rechazada
At Spring the the post method that receives the <Solicitud> object:
#RequestMapping(value = "/solicitudes/gestionarSolicitud/{estadoSol}", method = RequestMethod.POST, produces = "application/json")
public ResponseEntity<Object> setSolicitud(#RequestBody Solicitud solicitud, #PathVariable(value="estadoSol") int estadoSol ){
Optional<Solicitud> optionalSolicitud = solicitudService.gestionarSolicitud(solicitud, estadoSol);
if (optionalSolicitud.isPresent()) {
return new ResponseEntity<Object>(optionalSolicitud.get(), HttpStatus.OK);}
} else {
return new ResponseEntity<Object>(null , HttpStatus.OK);
}
}
At Android (front part) Solicitud Model:
public class Solicitud implements Serializable {
private int id;
private Date fecha;
private int estadoSolicitud; // 0 pendiente 1 Aceptada 2 Rechazada
//getters && setters...
}
At Android the request method that's request the post method to back:
public interface SolicitudService {
#POST("/solicitudes/gestionarSolicitud/{estadoSol}")
Call<Solicitud> gestionarSolitud( #Body Solicitud solicitud, #Path("estadoSol") int estadoSol);
}
At Android the function that uses the request method:
private void gestionarSolicitud(#NotNull Solicitud solicitud, int estadoSol) {
SolicitudService solicitudService = ApiClient.getClient().create(SolicitudService.class);
Call<Solicitud> call = solicitudService.gestionarSolitud(solicitud, estadoSol);
call.enqueue(new Callback<Solicitud>() {
#Override
public void onResponse(Call<Solicitud> call, Response<Solicitud> response) {
Solicitud solActualizada = response.body();
if (solActualizada != null && solActualizada.getEstadoSol() == estadoSol) {
if (estadoSol == 1)
Toast.makeText(context, "Usuario registrado correctamente", Toast.LENGTH_LONG).show();
else if (estadoSol == 2)
Toast.makeText(context, "Solicitud rechazada", Toast.LENGTH_LONG).show();
notifyDataSetChanged();
} else {
Toast.makeText(context, "Ups! Ha ocurrido un error", Toast.LENGTH_LONG).show();
}
}
#Override
public void onFailure(Call<Solicitud> call, Throwable t) {
Toast.makeText(context, "Ups! Ha ocurrido un error del servidor.", Toast.LENGTH_LONG).show();
}
});
}
I think you have to try Joda Time library as a common middleware for your date fields.
You haven't shown any actual code, so a definitive answer isn't possible, but you need to make sure that whatever you are using to serialize your java objects to Json on the Android side properly serializes Dates to ISO-8601 format.
Most mainstream Json serializers, e.g. Gson, will do that by default.
The exception is saying that the value you are sending from client side(android) is having different data type, what you are fetching in back-end (Spring).
At both end the datatype must be same.
Please try this
Spring Code : You can mention the date format with JsonFormat annotation
String DATE_FORMAT_MM_DD_YYYY = "MM/dd/yyyy"
#JsonFormat(pattern = DATE_FORMAT_MM_DD_YYYY)
private Date fetching_date;
For Android Code : Get the date and you can change the date formats using below code
You can define the date formats like this :
const val DATE_FORMAT_yyyy_MM_dd_HH_mm_ss_a = "yyyy-MM-dd HH:mm:ss a"
const val DATE_FORMAT_MMM_dd_yyyy = "MMM dd, yyyy"
const val DATE_FORMAT_MMM_dd_yyyy_HH_MM_AA = "MMM dd, yyyy hh:mm aa"
const val DATE_FORMAT_YYYY_MM_DD = "yyyy-MM-dd"
//Convertion of one date format to another
fun convertDateFormat(oldFormat: String, newFormat: String, dateString: String): String {
var sdf = SimpleDateFormat(oldFormat)
try {
val date = sdf.parse(dateString)
sdf = SimpleDateFormat(newFormat, getLocalForDateFormat())
return sdf.format(date)
} catch (e: Exception) {
e.printStackTrace()
}
return ""
}
Send the date from android to back-end in request.
I am providing a date input in MM/dd/yyyy format, the format produces an incorrect date on UI, this only happens with MM/dd/yyyy format, however, it is working fine if input will be in dd/MM/yyyy.
eg: if today's date 04/08/2020, then it is rendered as 07/09/2021, which is of course wrong date
The application using extjs3 as frontend and so the date picker.
function insSKUDate(element,textElement,img){
var selectHandler = function(myDP, date) {
var field = document.getElementById(textElement);
field.value = date.format('m/d/Y');
field.text = date.format('m/d/Y');
dateField = document.getElementById(textElement);
myDP.hide();
};
var myDP = new Ext.DatePicker(
{
startDay: 1,
minDate: new Date(),
listeners: {
'select':selectHandler
}
}
);
var innerdata = document.getElementById(element);
innerdata.innerHTML="";
myDP.render(element);
var clickHandler = function() {
myDP.show();
};
Ext.EventManager.on(img.id, 'click', clickHandler);
}
somewhere in HTML form
<td width="20%">
<input type="text" class="textbox"
value="<s:property value='skulaunchDate'/>"
name="skulaunchDate"
id="skulaunchDate" readonly="readonly"/>
<img style="vertical-align:text-bottom" src="images/calimg.jpg"
width="16" height="16"
onClick="insSKUDate('skulaunchDateSpan', 'skulaunchDate', this)"
id="skulaunchDateIcon"/>
<span id="skulaunchDateSpan"
style="position:absolute;z-index:1;width:50px;"></span>
<div id="skulaunchDateErrorMsg" align="left"
style="color:#FF0000"/>
</td>
Somewhere in my Struts' execute()
public String getSkulaunchDate() {
return skulaunchDate;
}
public void setSkulaunchDate(String skulaunchDate) {
this.skulaunchDate = skulaunchDate;
}
if (bean.getSkulaunchDate() != null)
setSkulaunchDate(dateUtil.getSQLDateToString(bean.getSkulaunchDate(), "MM/dd/yyyy"));//Replace dd/MM/yyyy to MM/dd/yyyy
// setSkulaunchDate(getSkuLaunchDateStrFormat(bean,dateUtil));//Replace dd/MM/yyyy to MM/dd/yyyy
System.out.println("3.getSkulaunchDate----"+ getSkulaunchDate());
setContactPersonName(bean.getContactPersonName());
setContactPersonPosition(bean.getContactPersonPosition());
setContactPersonEmail(bean.getContactPersonEmail());
setContactPersonNumber(bean.getContactPersonNumber());
setRemarks(bean.getRemarks());
setTpRemarks(bean.getTpRemarks());
try {
if(request_bean.getRequestDate() != null){
setRequest_date(dateUtil.getUtilDateToString(request_bean.getRequestDate(), "MM/dd/yyyy"));//Replace dd/MM/yyyy to MM/dd/yyyy
}
} catch (Exception ex) {
logger.error(ex.getStackTrace());
}
I have doubt on the below method, but it looks fine
public String getSQLDateToString(java.sql.Date date, String format) {
String result = null;
try {
result = new SimpleDateFormat(format).format(date);
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
It is found that the input is in SQL date having some problem while parsing, apart from this util date is working fine.
please suggest me the solution to rectify this.
The legacy date-time API is known to be confusing and error-prone. Since you are using Java-7, unfortunately, either you will have to live with it or you can backport the code using modern date-time API to Java-7 using ThreeTen-Backport library.
I recommend you address the following problems with your code:
Never use a date-time parsing/formatting API without a Locale.
If your method can not handle an exception (i.e. can not do something to recover from the failure), it should simply throw the exception so that the calling method can get an opportunity to handle it appropriately. Therefore, using e.printStackTrace() in your method, getSQLDateToString is a bad idea. By the way, SimpleDateFormat#format does not throw an exception. Probably, you got confused with SimpleDateFormat#parse which throws ParseException.
The following code incorporates these comments:
import java.text.SimpleDateFormat;
import java.util.Locale;
public class Main {
public static void main(String[] args) {
// Today
java.sql.Date date = new java.sql.Date(System.currentTimeMillis());
System.out.println(getSQLDateToString(date, "MM/dd/yyyy"));
System.out.println(getSQLDateToString(date, "dd/MM/yyyy"));
}
public static String getSQLDateToString(java.sql.Date date, String format) {
return new SimpleDateFormat(format, Locale.ENGLISH).format(date);
}
}
Output:
02/07/2021
07/02/2021
Using the modern date-time API
Use java.sql.Date#toLocalDate to convert a java.sql.Date to LocalDate.
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Locale;
public class Main {
public static void main(String[] args) {
// Today
java.sql.Date date = new java.sql.Date(System.currentTimeMillis());
System.out.println(getSQLDateToString(date, "MM/dd/yyyy"));
System.out.println(getSQLDateToString(date, "dd/MM/yyyy"));
}
public static String getSQLDateToString(java.sql.Date date, String format) {
LocalDate localDate = date.toLocalDate();
DateTimeFormatter dtf = DateTimeFormatter.ofPattern(format, Locale.ENGLISH);
return dtf.format(localDate);
}
}
Output:
02/07/2021
07/02/2021
Learn about the modern date-time API from Trail: Date Time.