教程集 www.jiaochengji.com
教程集 >  脚本编程  >  javascript  >  正文 javascript格式化日期时间 自定义格式化函数示例

javascript格式化日期时间 自定义格式化函数示例

发布时间:2015-07-09   编辑:jiaochengji.com
本文介绍了javascript格式化日期时间的方法,使用自定义格式化函数的例子,有需要的朋友参考下。

javascript默认的时间格式一般情况下不会用,所以需要进行格式化,本节总结了javascript时间格式化的方法。

可以利用javascript中date对象的内置方法来格式化,例如:
 

复制代码 代码示例:
var d = new date();
console.log(d); // 输出:mon nov 04 2013 21:50:33 gmt+0800 (中国标准时间)
console.log(d.todatestring()); // 日期字符串,输出:mon nov 04 2013
console.log(d.togmtstring()); // 格林威治时间,输出:mon, 04 nov 2013 14:03:05 gmt
console.log(d.toisostring()); // 国际标准组织(iso)格式,输出:2013-11-04t14:03:05.420z
console.log(d.tojson()); // 输出:2013-11-04t14:03:05.420z
console.log(d.tolocaledatestring()); // 转换为本地日期格式,视环境而定,输出:2013年11月4日
console.log(d.tolocalestring()); // 转换为本地日期和时间格式,视环境而定,输出:2013年11月4日 下午10:03:05
console.log(d.tolocaletimestring()); // 转换为本地时间格式,视环境而定,输出:下午10:03:05
console.log(d.tostring()); // 转换为字符串,输出:mon nov 04 2013 22:03:05 gmt+0800 (中国标准时间)
console.log(d.totimestring()); // 转换为时间字符串,输出:22:03:05 gmt+0800 (中国标准时间)
console.log(d.toutcstring()); // 转换为世界时间,输出:mon, 04 nov 2013 14:03:05 gmt

另外,也可以自定义函数来格式化时间,例如:
 

复制代码 代码示例:
date.prototype.format = function(format) {
  var date = {
    "m+": this.getmonth() + 1,
    "d+": this.getdate(),
    "h+": this.gethours(),
    "m+": this.getminutes(),
    "s+": this.getseconds(),
    "q+": math.floor((this.getmonth() + 3) / 3),
    "s+": this.getmilliseconds()
  };
  if (/(y+)/i.test(format)) {
    format = format.replace(regexp.$1, (this.getfullyear() + '').substr(4 - regexp.$1.length));
  }
  for (var k in date) {
    if (new regexp("(" + k + ")").test(format)) {
      format = format.replace(regexp.$1, regexp.$1.length == 1
        ? date[k] : ("00" + date[k]).substr(("" + date[k]).length));
    }
  }
  return format;
}
var d = new date().format('yyyy-mm-dd');
console.log(d); // 2013-11-04

您可能感兴趣的文章:
javascript 格式化时间日期函数代码
javascript日期对象格式化为字符串
javascript日期计算与格式化日期
js按指定格式显示日期时间的代码
javascript格式化日期时间 自定义格式化函数示例
javascript日期格式化简单例子
javascript 格式化时间日期函数
js字符串日期格式化为yyyy-mm-dd
php日期函数问题
PHP 5.2日期、时间和时区处理详解

[关闭]
~ ~