Java formating date output from db table - java

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.

Related

play framework : Pass date to view

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>

Java library for HTML to Java (POJO) conversion

Using Apache Velocity Api we can combine Java objects (Lists, POJOs etc.) with a (HTML) template and create the (HTML) output.
Is there any Java API that can help reverse engineer this ? The input of this API could be HTML output and the template used, the output should be the data (in Java/XML format) that was used to generate the output.
I am aware of HTTP Unit API, but this just lets me extract HTML elements (like Tables). I am looking for something that extracts the data based on some template.
You can use google protobuf in order to convert messages for different types. And it is very easy to define templates as well. I create JavaScript Objects using JSON.parse(), and in Java you can use protobuf to convert JSON to Java objects.
http://code.google.com/p/protobuf/
http://code.google.com/p/protobuf-java-format/
My answer won't probably be useful to the writer of this question (I have 5 years late so not the right timing I guess) but as this is the first result I found on Google when typing HTML to POJO, I think it will probably be useful for many other developers that might come across this answer.
Today, I just released (in the name of my company) an HTML to POJO complete framework that you can use to map HTML to any POJO class with simply some annotations. The library itself is quite handy and features many other things all the while being very pluggable. You can have a look to it right here : https://github.com/whimtrip/jwht-htmltopojo
How to use : Basics
Imagine we need to parse the following html page :
<html>
<head>
<title>A Simple HTML Document</title>
</head>
<body>
<div class="restaurant">
<h1>A la bonne Franquette</h1>
<p>French cuisine restaurant for gourmet of fellow french people</p>
<div class="location">
<p>in <span>London</span></p>
</div>
<p>Restaurant n*18,190. Ranked 113 out of 1,550 restaurants</p>
<div class="meals">
<div class="meal">
<p>Veal Cutlet</p>
<p rating-color="green">4.5/5 stars</p>
<p>Chef Mr. Frenchie</p>
</div>
<div class="meal">
<p>Ratatouille</p>
<p rating-color="orange">3.6/5 stars</p>
<p>Chef Mr. Frenchie and Mme. French-Cuisine</p>
</div>
</div>
</div>
</body>
</html>
Let's create the POJOs we want to map it to :
public class Restaurant {
#Selector( value = "div.restaurant > h1")
private String name;
#Selector( value = "div.restaurant > p:nth-child(2)")
private String description;
#Selector( value = "div.restaurant > div:nth-child(3) > p > span")
private String location;
#Selector(
value = "div.restaurant > p:nth-child(4)"
format = "^Restaurant n\*([0-9,]+). Ranked ([0-9,]+) out of ([0-9,]+) restaurants$",
indexForRegexPattern = 1,
useDeserializer = true,
deserializer = ReplacerDeserializer.class,
preConvert = true,
postConvert = false
)
// so that the number becomes a valid number as they are shown in this format : 18,190
#ReplaceWith(value = ",", with = "")
private Long id;
#Selector(
value = "div.restaurant > p:nth-child(4)"
format = "^Restaurant n\*([0-9,]+). Ranked ([0-9,]+) out of ([0-9,]+) restaurants$",
// This time, we want the second regex group and not the first one anymore
indexForRegexPattern = 2,
useDeserializer = true,
deserializer = ReplacerDeserializer.class,
preConvert = true,
postConvert = false
)
// so that the number becomes a valid number as they are shown in this format : 18,190
#ReplaceWith(value = ",", with = "")
private Integer rank;
#Selector(value = ".meal")
private List<Meal> meals;
// getters and setters
}
And now the Meal class as well :
public class Meal {
#Selector(value = "p:nth-child(1)")
private String name;
#Selector(
value = "p:nth-child(2)",
format = "^([0-9.]+)\/5 stars$",
indexForRegexPattern = 1
)
private Float stars;
#Selector(
value = "p:nth-child(2)",
// rating-color custom attribute can be used as well
attr = "rating-color"
)
private String ratingColor;
#Selector(
value = "p:nth-child(3)"
)
private String chefs;
// getters and setters.
}
We provided some more explanations on the above code on our github page.
For the moment, let's see how to scrap this.
private static final String MY_HTML_FILE = "my-html-file.html";
public static void main(String[] args) {
HtmlToPojoEngine htmlToPojoEngine = HtmlToPojoEngine.create();
HtmlAdapter<Restaurant> adapter = htmlToPojoEngine.adapter(Restaurant.class);
// If they were several restaurants in the same page,
// you would need to create a parent POJO containing
// a list of Restaurants as shown with the meals here
Restaurant restaurant = adapter.fromHtml(getHtmlBody());
// That's it, do some magic now!
}
private static String getHtmlBody() throws IOException {
byte[] encoded = Files.readAllBytes(Paths.get(MY_HTML_FILE));
return new String(encoded, Charset.forName("UTF-8"));
}
Another short example can be found here
Hope this will help someone out there!

dd/MM/yyyy date format in jsp by scriptlet

I want to show the date coming from data base in the jsp page in dd/MM/yyyy format. Here is my code in javascript.
$(document).ready(function(){
<%
SDateDTO sDTO = (SDateDTO) request.getAttribute("sDTO");
if(null != scholAvailDTO){
System.out.println(scholAvailDTO.getEndDate());
%>
var end = <%=scholAvailDTO.getEndDate() %>;
$("#endDateId").val(end);
<%
}
%>
});
In console it is coming 27/04/2010 but in jsp it is getting populated like 0.0033582089552238806 which is actually division result of the date. Any help will be appreciated. Thanks, Amit
Well yes - your Javascript will presumably be rendered to the browser as:
var end = 27/04/2010;
If you want it to be in a string literal then you'll need to add the quotes yourself:
var end = "<%=scholAvailDTO.getEndDate() %>";
Note that you'll need to be confident that the value itself doesn't have quotes - or other values which aren't appropriate for JavaScript - in there. I suspect there may well be a better approach than the above.
If getEndDate() returns java.util.Date object then, use DateFormat for get the formatted string and then wrap the value in quotes as below:
<%DateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");%>
var end = "<%=formatter.format(scholAvailDTO.getEndDate()) %>";
If getEndDate() returns java.lang.String then simply wrap the value in quotes as below:
var end = "<%=scholAvailDTO.getEndDate() %>";

DATE handiling from JSP to JAVA to PSQL and back

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

JSP Date to PostgreSQL Date JasperException

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".

Categories