This is the second week trying to find an answer to my problem... everything fine works except when inserting a date field to database problem... I am sure someone can help me! THANK YOU !
Database column is: campstart and it is a "Timestamp without time zone"
++++++++++ JSP page with the following:
... (some code) // Formatting the date:
SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy HH:mm");
... (some code) // getting input from webpage
<input name="start" type="text" value="<%= defaultCampaign.getCampstart() != null ? dateFormat.format(defaultCampaign.getCampstart()) : dateFormat.format(new java.util.Date()) %>">
... (more code)
++++++++++ On Java:
... (some code) // declaring variable
private java.util.Date campstart = null;
... (some code) // assigning data
public void setCampstart(java.util.Date aCampstart) {
this.campstart = aCampstart; }
public java.util.Date getCampstart() {
return this.campstart; }
... (some code) // writing to PostgreSQL +below is the line with problems+
pst.setTimestamp(10, new Timestamp(this.getCampstart().getTime()));
... (more code)
+++++++++
It works fine when I change the code line to the following (for debugging):
pst.setTimestamp(10, new Timestamp(new java.util.Date().getTime()));
The date Insert works perfectly, it writes to Database without errors. But, when I change the code to insert the user date, it gives me the following error:
org.apache.jasper.JasperException: Unable to convert string "04/07/2012 19:12" to class "java.util.Date" for attribute "campstart": Property Editor not registered with the PropertyEditorManager
Can someone please help me to figure out what I am doing wrong...
THANK YOU !!
Rob.
Got it to work when I changed the format on the date. For some reason it was sending it on the month like "7" instead of "07".
Related
I have an issue with saving correct Java LocalDates to a MySQL database. When I log the date, it shows the correct date, but when I save it for two different entities (User and Household),
Household always saves it as one day earlier (consistent and explainable by timezone diff), but
User saves a semi-random different date which I don't understand.
See image for examples of the correct date, household saved dat, user saved date and number of days difference between the user and household date can be seen in the following table. For the date 2017-04-01, the "random" version for the User entity even differs.
The dates are correct when running locally on my MacBook Pro, but the date differences occur in our Java 11 Google App Engine development or production environments. Could you help me understand why this is happening?
The date is received using a REST webservice that accepts a date as a ISO-formatted YYYY-MM-DD string as part of a UserRegistrationCommand class. This class then converts the string to a LocalDate object in its getMoveInDate method:
public class UserRegistrationCommand {
...
public String moveInDate;
...
public LocalDate getMoveInDate() {
if(moveInDate == null) {
return null;
}
try {
return LocalDate.parse(moveInDate, DateTimeFormatter.ISO_LOCAL_DATE);
} catch (Exception e) {
return null;
}
}
}
Using Spring JPA, I then save this date for an User and Household entity respectively to a MySQL database where the tables for these entities are using a DATE datatype.
When I log the date prior to saving, it shows the correct value. But when the date is saved in the database, the User table gets a date many days off, while the Household table gets a date that is one day prior to the submitted date.
(The dates in the code comments below refer to the first date example in my image)
Saving the User entity:
#Transactional
public User createUser(String email, String password, String firstName, String lastName, String language, Household household, LocalDate moveInDate, String redirectState) {
LOG.debug("Registering user {}, {}, moveInDate: {}", email, household, moveInDate != null ? moveInDate.toString() : "null"); // <-- Logs "Registering user ... moveInDate: 2017-08-01 ..."
[...]
Locale locale = localeProvider.matchAvailableLocale(language);
User user = new User(email, encodedPassword, firstName, lastName, locale, household, moveInDate, NotificationPreferences.defaultPreferences());
user.setRedirectState(redirectState);
Image profilePicture = avatarService.createProfilePicture(user.getNameInitials());
user.setProfilePicture(profilePicture);
return save(user); // <-- calls userRepository.save(user), but date is stored as 2017-07-27
}
Saving the household entity:
LOGGER.debug("ActivationCodeRegistrationStrategy.register: Setting moveInDate {} for household {} for user {}", cmd.getMoveInDate(), activationCode.getHousehold(), cmd.email); <-- logs "ActivationCodeRegistrationStrategy.register: Setting moveInDate 2017-08-01 ..."
householdService.setMoveInDate(activationCode.getHousehold(), cmd.getMoveInDate()); <-- but a date of 2017-07-31 is saved.
The householdService.setMoveInDate call just sets the date for the Household entity and saves it to database:
public void setMoveInDate(Household household, LocalDate moveInDate) {
household.setMoveInDate(moveInDate);
householdRepository.save(household);
}
This issue is coming from the MySQL Connector in java. Version 8.0.19 converts the date using the JVMs timezone which results in the 1 day off problem. This is resolved in the 8.0.20 patch. Read here https://dev.mysql.com/doc/relnotes/connector-j/8.0/en/
or you should change MySQL Connector as latest like now 8.0.28
Ok, first to say that I've been searching few days on how to resolve this problem and I've tried million ways but I think that neither of that working for me, or I'm missing something.
I have a db table with a column type date.
I have model class with a field Date.
public class Pacijent {
//..
private Date datum;
//getters and setters
}
And a Data access object for retrieving and storing into a model class like this:
ResultSet rs = ps.executeQuery();
while(rs.next()) {
Pacijent pacijent = new Pacijent();
//..
pacijent.setDatum(rs.getDate("datum"));
//..
pacijents.add(pacijent);
}
Next I set set attribute in controller and retrieve it in jsp page like ${param.paramName}
The problem is that it outputs in yyyy-MM-dd and I want it to show in dd-MM-yyyy. Can you please guide me how do I format that in a right way?
The JSTL fmt library has a formatDate tag for just this purpose. To use it, first put this directive in the <head> element of your JSP:
<%# taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
Then in the body of the page you can write something like
<fmt:formatDate value="${date}" pattern="dd-MM-yyyy"/>
The doc, such as it is, for fmt:formatDate is here. You may also need the info here
in order to figure out how to construct an appropriate format pattern.
This may not be optimal, but one option would be to expose a string getter in your Pacijent class which uses a SimpleDateFormat to generate the date string in the format you want for your presentation:
class Pacijent {
// other content
public String getDateFormatted() {
SimpleDateFormat sdf = new SimpleDateFormat("dd/M/yyyy");
String date = sdf.format(datum);
return date;
}
}
Then, access this getter from your JSP.
Ok, so after trying really hard for some days i am still not able to make this work.
This is the problem: I have a JSP which hosts a Google chart that is going to be constructed from data that is going to be sent through a Servlet. I'm using the Google Visualization Java libraries to implement this servlet.
Then i have this helper function that, taking some data stored in a list of objects, constructs a datatable. Following is the class that implements said function:
public class DataTableGenerator {
public static DataTable generateDatatable(List<AccesoUrl> accesos) {
DataTable data = new DataTable();
ArrayList<ColumnDescription> cd = new ArrayList<>();
cd.add(new ColumnDescription("fecha", ValueType.DATE, "Fecha"));
cd.add(new ColumnDescription("navegador", ValueType.TEXT, "Navegador"));
cd.add(new ColumnDescription("ip", ValueType.TEXT, "IP"));
cd.add(new ColumnDescription("os", ValueType.TEXT, "Sistema Operativo"));
data.addColumns(cd);
try {
for(AccesoUrl acceso : accesos) {
GregorianCalendar calendario = new GregorianCalendar();
calendario.setTimeZone(TimeZone.getTimeZone("GMT"));
data.addRowFromValues(calendario, acceso.getNavegador(), acceso.getIp(), acceso.getSistemaoperativo());
}
} catch (TypeMismatchException e) {
System.out.println(e);
}
return data;
}
}
Now, this piece of code should work, but instead i am getting this exception on my web server:
com.google.visualization.datasource.base.TypeMismatchException: Value type mismatch.
at com.google.visualization.datasource.datatable.value.ValueType.createValue(Unknown Source)
at com.google.visualization.datasource.datatable.DataTable.addRowFromValues(Unknown Source)
I'm at wit's end now. I have tried every variation i could find on Google so that my JSP displays this data on a Google Table type of chart. I have tried sending a date as a string, a date as a string formatted as a javascript date (i.e "Date(2015,4,4)" or "new Date(2015,4,4)"). I have tried using the DateValue object that comes with the java visualization library to construct the date as well (i.e new DateValue(2015,4,4)). I have also tried passing a Java Date as well. Nothing works, everything throws a TypeMismatchException.
I am sure it's the date that's giving me trouble because as soon as i remove the date column from the datatable everything runs fine with no exception and i can get my data displayed on the Google chart table.
So can anybody please tell me what exactly do i have to do in my Java code to be able to construct a datatable with a date cell?
Even I faced same issue. But it seems addRowFromValues() doesn't support DateValue(). I siwtched to addRow(TableRow). Didnt see any error's.
You can use something like below,
Sample Code:
DataTable data = new DataTable();
ArrayList<ColumnDescription> cd = new ArrayList<ColumnDescription>();
cd.add(new ColumnDescription("date", ValueType.DATE, "Executed Date"));
cd.add(new ColumnDescription("value", ValueType.NUMBER, "Duration "));
data.addColumns(cd);
TableRow tr = new TableRow();
tr.addCell(new DateValue(2015,7,7));
data.addRow(tr);
I need to pass the date parameter to view in play framework
My controller looks like
something.render(new Date());
And on my view what I've done is
#(myDate : Date)
<script lang="text/javascript">
var time = "#(myDate)";
</script>>
This time variable I further need to use in jQuery.
Thing is Play framework is converting the date to string object.
What I want is date object itself.
If I remove the quotes around "#(myDate)" Java script gives following output.
var backupTimeString = 2015-01-15 00:01:28.767;
Uncaught Syntax Error : expecte number
I really need the object to passed as Date object not as String represnetation of Date
1) If you work in local time, you could pass the time as a formatted string :
something.render( ... new java.text.SimpleDateFormat("yyyy/MM/dd hh:mm:ss").format(new java.util.Date()) ...)
and convert it to javascript date in the view :
<script>
var t = new Date("#mydate");
</script>
According to http://dygraphs.com/date-formats.html the format aaaa/mm/jj hh:mm:ss is the most robust.
2) In case you don't work in local time, recent browsers accept ISO-8601 date with offset from UTC, for example :
new Date('2015-01-22T12:00-0600')
3) As a last resort, you can pass a timestamp :
something.render(... new java.util.Date().getTime() ...)
<script>
var t = new Date(#mydate);
</script>
I am having a problem handling date variables when I write to PostgreSQL using JSP forms. There has been some great tips but still can not get it right. I believe that I am passing a String from JSP to JAVA where it is a Date "setter" and "getter" writing to PSQL on a "date without time zone" column.
Here is parts of the JSP code related to the Date:
.... (some code) ....
SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy HH:mm");
.... (mode code) ....
<%
if (action.equals("add")) {
.
.
.
newCampaign.setCampempDate(dateFormat.parse(request.getParameter("campemp")));
newCampaign.add();
}
%>
.... (more code) ....
<input name="campemp" type="text" class="datePickBox" id="campemp"
onBlur="javascript:checkFormat(this)" value="<%= defaultCampaign.getCampempDate() != null
? dateFormat.format(defaultCampaign.getCampempDate()) : dateFormat.format(new
java.util.Date()) %>" size=20>
.... (rest of code) ....
It is important to mention that on the input I am also using a calendar that passes the date with the correct format... this is another reason I am using a date field on the JSP side.
On the JAVA side:
.... (some code) ....
private java.util.Date campemp= null;
private SimpleDateFormat userDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
... (more code) ... ++ Set and Get ++
public void setCampempDate(java.util.Date aCampemp) {
this.campemp= aCampemp;
}
public java.util.Date getCampempDate() {
return this.campemp;
}
... (more code) ... ++ LOAD ++
public void load(ResultSet rs) throws SQLException {
this.setId(rs.getLong("campkeydbid"));
.
.
this.setCampempDate(rs.getDate("campemp"));
}
... (more code) ... ++ WRITE TO DB ++
public boolean add() throws SQLException {
boolean success = false;
if (costingEnabled) {
String call = "select " + getStoredProcedureMapper().getPrefix() + "_Add(?,?,?,?,?,?,?,?,?,?)";
DataSource ds = PoolMan.findDataSource("mydatabase");
Connection conn = null;
try {
conn = ds.getConnection();
PreparedStatement pst = conn.prepareStatement(call);
.
.
pst.setTimestamp(10, new Timestamp(this.getCampempDate().getTime()));
ResultSet rs = pst.executeQuery();
if (rs.next()) {
.
.
... (more code) ...
The "_Add" on the stored procedure is correct as it works if I "hardcode" the date on the pst.SetTimestamp
The error I am getting is the following:
org.apache.jasper.JasperException: Unable to convert string "04/07/2012 19:12" to class "java.util.Date" for attribute "campemp": Property Editor not registered with the PropertyEditorManager
Any ideas on a workaround to parse the String to Date without affecting the DB date field and JSP input will be greatly appreciated.. thank you very much.
Regards,
Rob
org.apache.jasper.JasperException: Unable to convert string "04/07/2012 19:12" to class "java.util.Date" for attribute "campemp": Property Editor not registered with the PropertyEditorManager
You are passing Date in String in 04/07/2012 19:12 format so you need to use
dd/MM/yyyy HH:mm
From the code you posted, It seems you are using
private SimpleDateFormat userDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
as format in SimpleDateFormat