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 相关文章推荐
一段实现页面上的图片延时加载的js代码
Feb 11 Javascript
IE6、IE7中获取Button元素的值的bug说明
Aug 28 Javascript
jquery cookie实现的简单换肤功能适合小网站
Aug 25 Javascript
JavaScript跨平台的开源框架NativeScript
Mar 24 Javascript
浅谈javascript中for in 和 for each in的区别
Apr 23 Javascript
js实现仿爱微网两级导航菜单效果代码
Aug 31 Javascript
15个常用的jquery代码片段
Dec 19 Javascript
浅析AngularJS Filter用法
Dec 28 Javascript
js实现文字滚动效果
Mar 03 Javascript
JS使用setInterval实现的简单计时器功能示例
Apr 19 Javascript
VUE 实现复制内容到剪贴板的两种方法
Apr 24 Javascript
vue循环中点击选中再点击取消(单选)的实现
Sep 10 Javascript
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
基于mysql的论坛(2)
2006/10/09 PHP
一致性哈希算法以及其PHP实现详细解析
2013/08/24 PHP
destoon实现调用当前栏目分类及子分类和三级分类的方法
2014/08/21 PHP
php 常用的系统函数
2017/02/07 PHP
静态页面的值传递(三部曲)
2006/09/25 Javascript
ExtJS 简介 让你知道extjs是什么
2008/12/29 Javascript
扩展easyui.datagrid,添加数据loading遮罩效果代码
2010/11/02 Javascript
JavaScript Title、alt提示(Tips)实现源码解读
2010/12/12 Javascript
jQuery bxCarousel实现图片滚动切换效果示例代码
2013/05/15 Javascript
固定网页背景图同时保持图片比例的思路代码
2013/08/15 Javascript
javascript四舍五入函数代码分享(保留后几位)
2013/12/10 Javascript
JS实现模仿微博发布效果实例代码
2013/12/16 Javascript
nodejs 实现模拟form表单上传文件
2014/07/14 NodeJs
javascript实现动态标签云
2015/10/16 Javascript
封装好的javascript前端分页插件pagination
2016/01/04 Javascript
jQuery实现漂亮实用的商品图片tips提示框效果(无图片箭头+阴影)
2016/04/16 Javascript
JavaScript的数据类型转换原则(干货)
2018/03/15 Javascript
解决vue移动端适配问题
2018/12/12 Javascript
Vue使用axios引起的后台session不同操作
2020/08/14 Javascript
[44:40]2018DOTA2亚洲邀请赛3月30日 小组赛A组Liquid VS OG
2018/03/31 DOTA
[05:06]DOTA2-DPC中国联赛 正赛 VG vs Magma选手采访
2021/03/11 DOTA
python批量修改文件后缀示例代码分享
2013/12/24 Python
Python随手笔记第一篇(2)之初识列表和元组
2016/01/23 Python
Python数据分析中Groupby用法之通过字典或Series进行分组的实例
2017/12/08 Python
Python模拟脉冲星伪信号频率实例代码
2018/01/03 Python
Python实现霍夫圆和椭圆变换代码详解
2018/01/12 Python
利用Opencv中Houghline方法实现直线检测
2018/02/11 Python
使用pyinstaller打包PyQt4程序遇到的问题及解决方法
2019/06/24 Python
HTML5 Canvas标签使用收录
2009/07/07 HTML / CSS
Swanson中国官网:美国斯旺森健康产品公司
2021/03/01 全球购物
捷克建筑材料网上商店:DEK.cz
2021/03/06 全球购物
2014年学习全国道德模范事迹思想汇报
2014/09/15 职场文书
奖学金感谢信
2015/01/21 职场文书
摩登时代观后感
2015/06/03 职场文书
Java数据开发辅助工具Docker与普通程序使用方法
2021/09/15 Java/Android
MySQL分区表实现按月份归类
2021/11/01 MySQL