Home  >  Article  >  Web Front-end  >  Introduction to the use of dateFormat

Introduction to the use of dateFormat

零下一度
零下一度Original
2017-07-24 10:09:562222browse

由于Jquery没有日期转换,所以要导入dateFormat.js这个文件,然后调用dateFormat(new Date(),'yyyy-mm-dd')方法即可;

// date必填, pattern默认'yyyy-MM-dd HH:mm:ss'
function dateFormat (date, pattern) {
  var week = {'0':'日', '1':'一', '2':'二', '3':'三', '4':'四', '5':'五', '6':'六'};
  pattern = pattern == null ? 'yyyy-MM-dd HH:mm:ss' : pattern;
  var o = {
    'M+': date.getMonth() + 1, // 月份
    'd+': date.getDate(), // 日
    'h+': date.getHours() % 12 === 0 ? 12 : date.getHours() % 12, // 小时
    'H+': date.getHours(), // 小时
    'm+': date.getMinutes(), // 分
    's+': date.getSeconds(), // 秒
    'q+': Math.floor((date.getMonth() + 3) / 3), // 季度
    'S': date.getMilliseconds() // 毫秒
  };
  if (/(y+)/.test(pattern)) {
    pattern = pattern.replace(RegExp.$1, (date.getFullYear() + '').substring(4 - RegExp.$1.length));
  }
  if (/(E+)/.test(pattern)) {
    pattern = pattern.replace(RegExp.$1, ((RegExp.$1.length > 1) ? (RegExp.$1.length > 2 ? '星期' : '周') : '') + week[date.getDay() + '']);
  }
  for (var k in o) {
    if (new RegExp('(' + k + ')').test(pattern)) {
      pattern = pattern.replace(RegExp.$1, (RegExp.$1.length === 1) ? (o[k]) : (('00' + o[k]).substring(('' + o[k]).length)));
    }
  }
  return pattern;
}



dateFormat(new Date());
// 输出: "2017-07-12 17:49:44"

dateFormat(new Date(), 'yyyy年 MM月 dd日 HH时 mm分 ss秒 S毫秒 周E 第q季度');
// 输出: "2017年 07月 12日 17时 55分 49秒 360毫秒 周三 第3季度"

The above is the detailed content of Introduction to the use of dateFormat. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn