Chinaunix首页 | 论坛 | 博客
  • 博客访问: 326760
  • 博文数量: 206
  • 博客积分: 1040
  • 博客等级: 少尉
  • 技术积分: 1756
  • 用 户 组: 普通用户
  • 注册时间: 2012-04-09 17:22
文章分类

全部博文(206)

文章存档

2015年(3)

2014年(147)

2013年(2)

2012年(54)

我的朋友

分类: 系统运维

2014-02-26 10:39:35

原文地址:JavaScript date 格式化输出 作者:huaius

Javascript中标准的时间日期输出格式为一长串,类似于“Thu Feb 01 0001 01:01:01 GMT+0800 (China Standard Time)”。这种格式稍显冗余。

下面的代码是通过prototype方式,向Date对象添加了一个自定义的函数来实现自定义的格式化输出

  1. <script language="JavaScript">
  2. Date.prototype.format = function(format) //author: meizz
  3. {
  4.   var o = {
  5.     "M+" : this.getMonth()+1, //month
  6.     "d+" : this.getDate(), //day
  7.     "h+" : this.getHours(), //hour
  8.     "m+" : this.getMinutes(), //minute
  9.     "s+" : this.getSeconds(), //second
  10.     "q+" : Math.floor((this.getMonth()+3)/3), //quarter
  11.     "S" : this.getMilliseconds() //millisecond
  12.   }
  13.   if(/(y+)/.test(format)) format=format.replace(RegExp.$1,
  14.     (this.getFullYear()+"").substr(4 - RegExp.$1.length));
  15.   for(var k in o)if(new RegExp("("+ k +")").test(format))
  16.     format = format.replace(RegExp.$1,
  17.       RegExp.$1.length==1 ? o[k] :
  18.         ("00"+ o[k]).substr((""+ o[k]).length));
  19.   return format;
  20. }
  21. alert(new Date().format("yyyy-MM-dd"));
  22. alert(new Date("january 12 2008 11:12:30").format("yyyy-MM-dd hh:mm:ss"));
  23. </script>

还有一种方法,是通过toISOString函数,它返回一个ISO标准的格林尼治时间,格式形如2014-06-05T03:23:08.882Z,所以要格式化一下

  1. new Date().toISOString().replace(/T/, ' ').replace(/\..+/, '')
阅读(970) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~