Java从服务器上获取时间,动态在jsp页面显示

Java获取服务器时间,动态显示到jsp页面,大家都是到Java只能获取一次,到页面的时间是静态的,不过通过js和Java的合作,巧妙地实现此功能

 
  
本人是给电视做系统,客户要求页面能显示时间,因为电视浏览器获取的时间不对,没办法只能从服务器获取时间,但是问题来了,服务器的时间获取一次就成静态的了,客户不满意,但也没办法,只能这样。不过这个问题在我这老惦记着,今天看到有个例子,说把Java获取服务器的时间转化成毫秒,然后用js每一秒刷新一次就可以动态显示,所以就有了下面的
 
  
 
  
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>





<%@page import="java.text.SimpleDateFormat;"%>

<%

String path = request.getContextPath();

String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";

%>





<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

<html>

  <head>

    <base href="<%=basePath%>">

    

    <title>My JSP 'index.jsp' starting page</title>

<meta http-equiv="pragma" content="no-cache">

<meta http-equiv="cache-control" content="no-cache">

<meta http-equiv="expires" content="0">    

<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">

<meta http-equiv="description" content="This is my page">

<!--

<link rel="stylesheet" type="text/css" href="styles.css">

-->

  </head>

  

  <body>

    <%

      Calendar rightNow = Calendar.getInstance();

SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm");

%>

<script language="javascript"> 

//从服务器上获取初始时间 

var currentDate = new Date(<%=new java.util.Date().getTime()%>); 





function run() 

{ 

currentDate.setSeconds(currentDate.getSeconds()+1); 

var time = "";

var year = currentDate.getFullYear();

var month = currentDate.getMonth() + 1;

var day = currentDate.getDate();

var hour = currentDate.getHours();

var minute = currentDate.getMinutes();

var second = currentDate.getSeconds();

if(hour < 10){

time += "0" + hour;

}else{

time += hour;

}

time += ":";

if(minute < 10){

time += "0" + minute;

}else{

time += minute;

}

time += ":";

if(second < 10){

time += "0" + second;

}else{

time += second;

}

document.getElementById("dt").innerHTML = year+"年"+month+"月"+day+"日" + time;     

} 

window.setInterval("run();", 1000); 

</script> 

<div id="dt">自动显示时间。。。。</div>

  </body>

</html>

你可能感兴趣的:(java)