HTML / JSP Doubt, webpage print date
I made a function that displays the date on a webpage and I uploaded it to some server ...
But when I changed the date of my system, I noticed that the date depends on the client machine.
Is it not possible to get the date from the real time server and insert this code into my program.
Hope I can explain my doubts. Please give some solution to this with a small sample of code ... that would be helpful.
Thank you very much.
a source to share
If you wrote it in javascript, ok ... this is always done on the client side. If you are calculating the date with javascript too late this code is gone.
To solve this problem, you will need to force your js function to receive data via parameters and that the data should be calculated on the server side.
You can do something like.
<%@ page import ="java.util.Date" %><%--Imports date --%>
<% Date date = new Date();
String strdate = date.toString();//could be formatted using SimpleDateFormat.
%>
<!--must be inside a form -->
<input type="text" value="javascript:showDate('<%=strdate%>');"/>
<!--must be inside a table-->
<td>javascript:showDate(<%=strdate%>);</td>
Or more elegantly, get the server date in your java class and write to it:
//formattedDate is defined above, in the format you like the most. Could be a
//java.util.date or a String
request.setDate("date",formattedDate);
And then, in your jsp using for example JSTL
<c:out value="${formattedDate}"/>
Or
<% //this java code is run on the server side.
String strdate = (String)request.getAttribute("date");
%>
<%=strdate%><!-- prints strdate to jsp. Could put it in a table, form, etc -->
EDIT . In response to your comment, you should:
<%--Imports java packages --%>
<%@ page import ="java.util.Date" %>
<%@ page import ="java.text.SimpleDateFormat"%>
<%-- Java code --%>
<% Date date = new Date();
Calendar calendar = Calendar.getInstance(TIME_ZONE).setTime(date);
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yy");
String strdate = sdf.format(calendar.getTime());
%>
<html>
<body>
<!-- Does not need to use javascript. All work is done on the server side.-->
<table>
<tr>
<td><%=strdate%></td>
</tr>
</table>
</body>
</html>
I have no idea what your timezone is, but I'm sure you do. Calendar.getInstance () takes a TimeZone instance as a parameter. This should do it
Take a look:
http://java.sun.com/javase/6/docs/api/java/util/TimeZone.html
http://java.sun.com/javase/6/docs/api/java/util/Calendar.html
a source to share