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() %>";
Related
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.
I am trying to parse HTML that comes to me as a giant String. When I get to Line 13, NodeChild page = it.parent()
I am able to find the key that I am looking for, but the data comes to me like This Is Value One In My KeyThis is Value Two in my KeyThis is Value Three In My Key and so on. I see a recurring trend where the seperator between the two is always UppercaseUppercase (withoutSpaces).
I would like to put it into an ArrayList one way or another. Is there a method that I am missing from the docs that is able to automatically do this? Is there a better way to parse this together?
class htmlParsingStuff{
private def slurper = new XmlSlurper(new Parser())
private void slurpItUp(String rawHTMLString){
ArrayList urlList = []
def htmlParser = slurper.parseText(rawHTMLString)
htmlParser.depthFirst().findAll() {
//Loop through all of the HTML Tags to get to the key that I am looking for
//EDIT: I see that I am able to iterate through the parent object, I just need a way to figure out how to get into that object
boolean trigger = it.text() == 'someKey'
if (trigger){
//I found the key that I am looking for
NodeChild page = it.parent()
page = page.replace('someKey', '')
LazyMap row = ["page": page, "type": "Some Type"]
urlList.add(row)
}
}
}
}
I can't provide you with working code since I don't know your specific html.
But: don't use XmlSlurper for parsing HTML, HTML is not well formed and therefor XmlSlurper is not the right tool for the job.
For HTML use a library like JSoup. You will find it much easier to use especially if you have some JQuery knowledge. Since you didn't post your HTML snippet I made up my own example:
#Grab(group='org.jsoup', module='jsoup', version='1.10.1')
import org.jsoup.Jsoup
def html = """
<html>
<body>
<table>
<tr><td>Key 1</td></tr>
<tr><td>Key 2</td></tr>
<tr><td>Key 3</td></tr>
<tr><td>Key 4</td></tr>
<tr><td>Key 5</td></tr>
</table>
</body>
</html>"""
def doc = Jsoup.parse(html)
def elements = doc.select('td')
def result = elements.collect {it.text()}
// contains ['Key 1', 'Key 2', 'Key 3', 'Key 4', 'Key 5']
To manipulate the document you would use
def doc = Jsoup.parse(html)
def elements = doc.select('td')
elements.each { oldElement ->
def newElement = new Element(Tag.valueOf('td'), '')
newElement.text('Another key')
oldElement.replaceWith(newElement)
}
println doc.outerHtml()
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 attempting to write an example JSP page for myself (very new to jsp), and have gone over an example to write one, but how do I get time to consistently update?
here is my snippet of code:
<body>
<%
java.text.DateFormat df = new java.text.SimpleDateFormat(
"HH:mm:ss:SS z MM/dd/yyyy");
Calendar cal = Calendar.getInstance();
%>
<h1>
Current Date and Time:
<%=df.format(cal.getTime())%>
</h1>
</body>
By the way i'm using a tomcat server to deploy this
function updateYourTime() {
var now = new Date(),
months = ['January', 'February', '...'];
time = now.getHours() + ':' + now.getMinutes(),
date = [now.getDate(),
months[now.getMonth()],
now.getFullYear()].join(' ');
document.getElementById('currentTime').innerHTML = [date, time].join(' / ');
setTimeout(updateYourTime, 1000);//This method will call for every second
}
updateYourTime(); // initial call
see here for details
<div id="currentTime"></time>
do you mean to show clock in your pages?
you can use java script.
here is an example
to show server clock in clients jsp use this javascripcode with java
Add a label where ever you want to show the server Time
<strong>Server Time : </strong><label id="timelable"></label>
And then add the following java script code at the end of the jsp inside the body tag
<script type="text/javascript">
var myVar = setInterval(function(){ myTimer() }, 1000);
var jsVar= <%=java.util.Calendar.getInstance().getTimeInMillis()%>;
var timeZoneOffset=<%=java.util.TimeZone.getDefault().getOffset(System.currentTimeMillis())%>;
jsVar=jsVar+timeZoneOffset;
function myTimer() {
jsVar=jsVar+1000;
var d = new Date(jsVar);
var t=d.toUTCString();
document.getElementById("timelable").innerHTML = t;
}
</script>
Thats it now you will see the server time running in you jsp.
I am using jquery Datatables plugin. I followed the link http://www.codeproject.com/Articles/190718/jQuery-DataTables-and-J2EE-web-application-integra
I am passing a Date in the JSON object to the datatables plugin. The format from webservice call is like
"Sat Jan 10 00:08:00 EST 2009"
, I need to strip off the time, EST and the day, I mean it should look something like
"Jan 10, 2009"
and the column is sorted on the server side. All I need is to strip off the data on the fly on the client side. I am still in the process of learning datatables plugin, I am not sure of implementing this. Experts please point me to the right direction.
[Edit] Since it looks like the date comes back from the server as a string then you're easiest solution is probably a regular expression. Try this:
function reformatDate(dateStr) {
var r = /^\w{3}\s+(\w{3})\s+(\d{1,2})\s+.*?(\d{4})$/
, m = (''+dateStr).match(r);
return (m) ? m[1]+' '+m[2]+', '+m[3] : dateStr;
}
[Original] Assuming you are working with an actual Date object and you don't want to incur the overhead of a proper JavaScript date wrangling library (such as the excellent Datejs) you could format the date like so:
var formatDate = (function() {
var months = ['Jan', 'Feb', 'Mar', 'Apr', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
return function(dt) {
return months[dt.getMonth()] + ' ' + dt.getDate() + ', ' + dt.getFullYear();
};
})();
formatDate(new Date()); // => "Mar 15, 2012"
I'm not sure if you can do this with bServerSide set to true but you might be able to setup column definitions using the aoColumns option for the datatable and then apply column rendering via
fnRender: function (o, val) {
parse your date here...
return newDateString;
}