日期在jsp的type表示_java web中日期Date类型在页面中格式化显示的三种方式

一般我们经常需要在将服务器端的Date类型,传到页面进行显示,这就涉及到一个如何格式化显示Date类型的问题,一般我们有三种方式进行:

1)在服务端使用SimpleDateFormat等类格式化成字符串,然后传给客户端,这样的话,需要将Date类型修改为String,或者增加一个String字段专门保存Date的字符串;

2)使用jstl的fmt标签库进行格式化,缺点是只能在jsp页面中进行,html页面就无能为力了,而且要导入标签;

3)在客户端使用javascript进行格式化,这种方式任何时候都能够很好的处理;

下面直接上代码:

js date format

*{margin:0;padding:0;}

#wrapper{margin:50px auto;width:300px;border:1px solid green;}

#wrapper div + div{margin:2px 0 0 2px;border-top:1px solid gray;}

#wrapper div:nth-child(even){color:#666;}

Date birthday = new Date();

request.setAttribute("birthday", birthday);

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

String birthStr = sdf.format(birthday);

request.setAttribute("birthStr", birthStr);

out.println(birthday);

%>

Date.prototype.format = function (fmt) {

var o = {

"M+": this.getMonth() + 1, // 月份

"d+": this.getDate(), //日

"H+": this.getHours(), //24小时制

"h+" : this.getHours()%12 == 0 ? 12 : this.getHours()%12, //12小时制

"m+": this.getMinutes(), //分

"s+": this.getSeconds(), //秒

"q+": Math.floor((this.getMonth() + 3) / 3), //季度

"S": this.getMilliseconds() //毫秒

};

if (/(y+)/.test(fmt))

fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));

for (var k in o)

if (new RegExp("(" + k + ")").test(fmt))

fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k])

: (("00" + o[k]).substr(("" + o[k]).length)));

return fmt;

}

var time1 = new Date().format("yyyy-MM-dd");

var time2 = new Date().format("yyyy-MM-dd hh:mm:ss");

var time3 = new Date().format("yyyy-MM-dd HH:mm:ss");

var time4 = new Date().format("yyyy-MM-dd HH:mm:ss S");

var time5 = new Date(1145667888).format("yyyy-MM-dd HH:mm:ss S");

$("#dateformat").text(time1);

$("#dateformat2").text(time2);

$("#dateformat3").text(time3);

$("#dateformat4").text(time4);

$("#dateformat5").text(time5);

$("#dateformat8").text(new Date("${birthday}").format("yyyy-MM-dd HH:mm:ss S"));

上面代码演示了三种方法来进行Date类型的字段如何在页面上格式化显示的问题。效果如下:

上面的代码有几点值得注意:

1)有时我们传的是json格式的Date类型,此时传递的其实是毫秒数,也可以利用javascript进行格式化:new Date(1145667888).format("yyyy-MM-dd HH:mm:ss S");

2)#wrapper div + div{margin:2px 0 0 2px;border-top:1px solid gray;}  这是一个非第一个选择符,意思是,#wrapper下的第一个div紧邻的所有的div,也就是#wrapper下的除了第一个div之外的div, 设置他们的 border-top,来显示成下划线的效果;

3)#wrapper div:nth-child(even){color:#666;} 这是一个CSS的伪选择符,相似的还有 :first-child  :last-child  :nth-child(3)  :nth-child(odd),对应到jquery中也有相似的东西;

4)js格式化Date的处理,是通过在其原型上增加方法 Date.prototype.format 来进行的;

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值