javascript日期格式化方法汇总


Posted in Javascript onOctober 04, 2015

方法一:

// 对Date的扩展,将 Date 转化为指定格式的String
// 月(M)、日(d)、小时(h)、分(m)、秒(s)、季度(q) 可以用 1-2 个占位符, 
// 年(y)可以用 1-4 个占位符,毫秒(S)只能用 1 个占位符(是 1-3 位的数字) 
// 例子: 
// (new Date()).Format("yyyy-MM-dd hh:mm:ss.S") ==> 2006-07-02 08:09:04.423 
// (new Date()).Format("yyyy-M-d h:m:s.S")   ==> 2006-7-2 8:9:4.18 
Date.prototype.Format = function (fmt) { //author: meizz 
  var o = {
    "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+)/.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"); 

方法二:

<script language="javascript" type="text/javascript"> 
<!-- /** * 对Date的扩展,将 Date 转化为指定格式的String * 月(M)、日(d)、12小时(h)、24小时(H)、分(m)、秒(s)、周(E)、季度(q)
  可以用 1-2 个占位符 * 年(y)可以用 1-4 个占位符,毫秒(S)只能用 1 个占位符(是 1-3 位的数字) * eg: * (new
  Date()).pattern("yyyy-MM-dd hh:mm:ss.S")==> 2006-07-02 08:09:04.423   
 * (new Date()).pattern("yyyy-MM-dd E HH:mm:ss") ==> 2009-03-10 二 20:09:04   
 * (new Date()).pattern("yyyy-MM-dd EE hh:mm:ss") ==> 2009-03-10 周二 08:09:04   
 * (new Date()).pattern("yyyy-MM-dd EEE hh:mm:ss") ==> 2009-03-10 星期二 08:09:04   
 * (new Date()).pattern("yyyy-M-d h:m:s.S") ==> 2006-7-2 8:9:4.18   
 */    
Date.prototype.pattern=function(fmt) {     
  var o = {     
  "M+" : this.getMonth()+1, //月份     
  "d+" : this.getDate(), //日     
  "h+" : this.getHours()%12 == 0 ? 12 : this.getHours()%12, //小时     
  "H+" : this.getHours(), //小时     
  "m+" : this.getMinutes(), //分     
  "s+" : this.getSeconds(), //秒     
  "q+" : Math.floor((this.getMonth()+3)/3), //季度     
  "S" : this.getMilliseconds() //毫秒     
  };     
  var week = {     
  "0" : "/u65e5",     
  "1" : "/u4e00",     
  "2" : "/u4e8c",     
  "3" : "/u4e09",     
  "4" : "/u56db",     
  "5" : "/u4e94",     
  "6" : "/u516d"    
  };     
  if(/(y+)/.test(fmt)){     
    fmt=fmt.replace(RegExp.$1, (this.getFullYear()+"").substr(4 - RegExp.$1.length));     
  }     
  if(/(E+)/.test(fmt)){     
    fmt=fmt.replace(RegExp.$1, ((RegExp.$1.length>1) ? (RegExp.$1.length>2 ? "/u661f/u671f" : "/u5468") : "")+week[this.getDay()+""]);     
  }     
  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 date = new Date();   
window.alert(date.pattern("yyyy-MM-dd hh:mm:ss"));
// -->
</script>

方法三:

Date.prototype.format = function (mask) { 
  var d = this;
  var zeroize = function (value, length) {
      if (!length) length = 2;
      value = String(value);
      for (var i = 0, zeros = ''; i < (length - value.length); i++) {
        zeros += '0';
      }
      return zeros + value;
    };
  return mask.replace(/"[^"]*"|'[^']*'|/b ( ? : d {
    1, 4
  } | m {
    1, 4
  } | yy( ? : yy) ? | ([hHMstT]) / 1 ? | [lLZ]) / b / g, function ($0) {
    switch ($0) {
    case 'd':
      return d.getDate();
    case 'dd':
      return zeroize(d.getDate());
    case 'ddd':
      return ['Sun', 'Mon', 'Tue', 'Wed', 'Thr', 'Fri', 'Sat'][d.getDay()];
    case 'dddd':
      return ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'][d.getDay()];
    case 'M':
      return d.getMonth() + 1;
    case 'MM':
      return zeroize(d.getMonth() + 1);
    case 'MMM':
      return ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'][d.getMonth()];
    case 'MMMM':
      return ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'][d.getMonth()];
    case 'yy':
      return String(d.getFullYear()).substr(2);
    case 'yyyy':
      return d.getFullYear();
    case 'h':
      return d.getHours() % 12 || 12;
    case 'hh':
      return zeroize(d.getHours() % 12 || 12);
    case 'H':
      return d.getHours();
    case 'HH':
      return zeroize(d.getHours());
    case 'm':
      return d.getMinutes();
    case 'mm':
      return zeroize(d.getMinutes());
    case 's':
      return d.getSeconds();
    case 'ss':
      return zeroize(d.getSeconds());
    case 'l':
      return zeroize(d.getMilliseconds(), 3);
    case 'L':
      var m = d.getMilliseconds();
      if (m > 99) m = Math.round(m / 10);
      return zeroize(m);
    case 'tt':
      return d.getHours() < 12 ? 'am' : 'pm';
    case 'TT':
      return d.getHours() < 12 ? 'AM' : 'PM';
    case 'Z':
      return d.toUTCString().match(/[A-Z]+$/);
      // Return quoted strings with the surrounding quotes removed   
    default:
      return $0.substr(1, $0.length - 2);
    }
  });
};

方法四:

<script type="text/javascript">
var date = new Date();
document.writeln(date);
//Thu Jan 08 2015 01:25:53 GMT+0800 (中国标准时间)
document.writeln(Date.parse());
//NaN
document.writeln(Date.parse('6/10/2014'));
//1402329600000 毫秒数
document.writeln(Date.parse('Thu Jan 08 2015 01:25:53'));
//1420651553000 毫秒数
document.writeln(Date.UTC());
//NaN
//日期格式化方法
document.writeln('<br/>');
document.writeln(date.toDateString());
//Thu Jan 08 2015
document.writeln('<br/>')
document.writeln(date.toTimeString());
//01:39:08 GMT+0800 (中国标准时间)
document.writeln('<br/>')
document.writeln(date.toLocaleDateString());
//2015年1月8日
document.writeln('<br/>')
document.writeln(date.toLocaleTimeString());
//上午1:39:08
document.writeln('<br/>')
document.writeln(date.toUTCString());
//Wed, 07 Jan 2015 17:39:08 GMT
//一些set,get方法
</script>

方法五:

Date.prototype.Format = function(formatStr) {
var str = formatStr;
var Week = ['日', '一', '二', '三', '四', '五', '六'];
str = str.replace(/yyyy|YYYY/, this.getFullYear());
str = str.replace(/yy|YY/, (this.getYear() % 100) > 9 ? (this.getYear() % 100).toString() : '0' + (this.getYear() % 100));
str = str.replace(/MM/, (this.getMonth() + 1) > 9 ? (this.getMonth() + 1).toString() : '0' + (this.getMonth() + 1));
str = str.replace(/M/g, (this.getMonth() + 1));
str = str.replace(/w|W/g, Week[this.getDay()]);
str = str.replace(/dd|DD/, this.getDate() > 9 ? this.getDate().toString() : '0' + this.getDate());
str = str.replace(/d|D/g, this.getDate());
str = str.replace(/hh|HH/, this.getHours() > 9 ? this.getHours().toString() : '0' + this.getHours());
str = str.replace(/h|H/g, this.getHours());
str = str.replace(/mm/, this.getMinutes() > 9 ? this.getMinutes().toString() : '0' + this.getMinutes());
str = str.replace(/m/g, this.getMinutes());
str = str.replace(/ss|SS/, this.getSeconds() > 9 ? this.getSeconds().toString() : '0' + this.getSeconds());
str = str.replace(/s|S/g, this.getSeconds());
return str
}

方法六:

Date.prototype.Format = function(formatStr) {
var str = formatStr;
var Week = ['日', '一', '二', '三', '四', '五', '六'];
str = str.replace(/yyyy|YYYY/, this.getFullYear());
str = str.replace(/yy|YY/, (this.getYear() % 100) > 9 ? (this.getYear() % 100).toString() : '0' + (this.getYear() % 100));
str = str.replace(/MM/, (this.getMonth() + 1) > 9 ? (this.getMonth() + 1).toString() : '0' + (this.getMonth() + 1));
str = str.replace(/M/g, (this.getMonth() + 1));
str = str.replace(/w|W/g, Week[this.getDay()]);
str = str.replace(/dd|DD/, this.getDate() > 9 ? this.getDate().toString() : '0' + this.getDate());
str = str.replace(/d|D/g, this.getDate());
str = str.replace(/hh|HH/, this.getHours() > 9 ? this.getHours().toString() : '0' + this.getHours());
str = str.replace(/h|H/g, this.getHours());
str = str.replace(/mm/, this.getMinutes() > 9 ? this.getMinutes().toString() : '0' + this.getMinutes());
str = str.replace(/m/g, this.getMinutes());
str = str.replace(/ss|SS/, this.getSeconds() > 9 ? this.getSeconds().toString() : '0' + this.getSeconds());
str = str.replace(/s|S/g, this.getSeconds());
return str
}

方法七:

/*
1、< 60s, 显示为“刚刚”
2、>= 1min && < 60 min, 显示与当前时间差“XX分钟前”
3、>= 60min && < 1day, 显示与当前时间差“今天 XX:XX”
4、>= 1day && < 1year, 显示日期“XX月XX日 XX:XX”
5、>= 1year, 显示具体日期“XXXX年XX月XX日 XX:XX”
*/
function timeFormat(time){
var date = new Date(time),
curDate = new Date(),
year = date.getFullYear(),
month = date.getMonth() + 10,
day = date.getDate(),
hour = date.getHours(),
minute = date.getMinutes(),
curYear = curDate.getFullYear(),
curHour = curDate.getHours(),
timeStr;
 
if(year < curYear){
timeStr = year +'年'+ month +'月'+ day +'日 '+ hour +':'+ minute;
}else{
var pastTime = curDate - date,
pastH = pastTime/3600000;
 
if(pastH > curHour){
timeStr = month +'月'+ day +'日 '+ hour +':'+ minute;
}else if(pastH >= 1){
timeStr = '今天 ' + hour +':'+ minute +'分';
}else{
var pastM = curDate.getMinutes() - minute;
if(pastM > 1){
timeStr = pastM +'分钟前';
}else{
timeStr = '刚刚';
}
}
}
return timeStr;
}

是不是第七种更加的个性化一些呢,个人推荐这种

Javascript 相关文章推荐
javascript while语句和do while语句的区别分析
Dec 08 Javascript
JavaScript 程序编码规范
Nov 23 Javascript
JQuery文本框高亮显示插件代码
Apr 02 Javascript
javascript的console.log()用法小结
May 31 Javascript
js与运算符和或运算符的妙用
Feb 14 Javascript
jQuery动画出现连续触发、滞后反复执行的解决方法
Jan 28 Javascript
jQuery中的siblings用法实例分析
Dec 24 Javascript
js模仿java的Map集合详解
Jan 06 Javascript
ActiveX控件的使用-js实现打印超市小票功能代码详解
Nov 22 Javascript
关于laydate.js加载laydate.css路径错误问题解决
Dec 27 Javascript
javascript json对象小技巧之键名作为变量用法分析
Nov 11 Javascript
详解vue身份认证管理和租户管理
May 25 Vue.js
jQuery插件Timelinr 实现时间轴特效
Oct 04 #Javascript
jquery 实现输入邮箱时自动补全下拉提示功能
Oct 04 #Javascript
使用 JavaScript 进行函数式编程 (一) 翻译
Oct 02 #Javascript
Clipboard.js 无需Flash的JavaScript复制粘贴库
Oct 02 #Javascript
jQuery网页右侧广告跟随滚动代码分享
Apr 20 #Javascript
jQuery+PHP星级评分实现方法
Oct 02 #Javascript
谈谈JSON对象和字符串之间的相互转换JSON.stringify(obj)和JSON.parse(string)
Oct 01 #Javascript
You might like
PHP4之真OO
2006/10/09 PHP
php 三维饼图的实现代码
2008/09/28 PHP
jQuery+php实现ajax文件即时上传的详解
2013/06/17 PHP
跟我学Laravel之安装Laravel
2014/10/15 PHP
JS操作图片(增,删,改) 例子
2013/04/17 Javascript
JavaScript实现url地址自动检测并添加URL链接示例代码
2013/11/12 Javascript
将form表单中的元素转换成对象的方法适用表单提交
2014/05/02 Javascript
JavaScript中停止执行setInterval和setTimeout事件的方法
2015/05/14 Javascript
微信公众平台开发教程(六)获取个性二维码的实例
2016/12/02 Javascript
JS中传递参数的几种不同方法比较
2017/01/20 Javascript
js实现关闭网页出现是否离开提示
2017/12/07 Javascript
vue中选项卡点击切换且能滑动切换功能的实现代码
2018/11/25 Javascript
JavaScript键盘事件响应顺序详解
2019/09/30 Javascript
Vue3.0 响应式系统源码逐行分析讲解
2019/10/14 Javascript
[01:14:12]2018DOTA2亚洲邀请赛4.7 总决赛 LGD vs Mineski 第二场
2018/04/09 DOTA
[50:34]VGJ.T vs Fnatic 2018国际邀请赛小组赛BO2 第二场 8.16
2018/08/17 DOTA
python统计文本文件内单词数量的方法
2015/05/30 Python
简单介绍使用Python解析并修改XML文档的方法
2015/10/15 Python
Python使用poplib模块和smtplib模块收发电子邮件的教程
2016/07/02 Python
Python读取图片属性信息的实现方法
2016/09/11 Python
Python 3.x 判断 dict 是否包含某键值的实例讲解
2018/07/06 Python
python3.6 如何将list存入txt后再读出list的方法
2019/07/02 Python
python 设置xlabel,ylabel 坐标轴字体大小,字体类型
2019/07/23 Python
tensorflow之自定义神经网络层实例
2020/02/07 Python
详解python polyscope库的安装和例程
2020/11/13 Python
德国W家官网,可直邮中国的母婴商城:Windeln.de
2021/03/03 全球购物
Ajax和javascript的区别
2013/07/20 面试题
高校十八大报告感想
2014/01/27 职场文书
党的群众路线学习材料
2014/05/16 职场文书
植树节标语
2014/06/27 职场文书
酒店爱岗敬业演讲稿
2014/09/02 职场文书
检察院对照“四风”认真查找问题落实整改措施
2014/09/26 职场文书
2015年社区科普工作总结
2015/05/13 职场文书
python opencv通过4坐标剪裁图片
2021/06/05 Python
Go 语言下基于Redis分布式锁的实现方式
2021/06/28 Golang
MongoDB支持的数据类型
2022/04/11 MongoDB